# JMathLabTutorial:9 Vectors

# Vectors

Vector types are either used for multidimensional objects, or for simultaneous calculations on large numbers of data, e.g. for statistical problems. In this chapter we discuss this latter aspect.

Vectors are marked with square brackets. The elements are entered as comma-separated list. The commas may be left if the elements can be distinguished in a unique manner:

Colon and the function line space are used to define ranges of numbers as vectors.

with the outputs:

Vectors are often used to achieve fairly complex data manipulation effects. "Colon notation" (which is used both to generate vectors) and subscripting by vectors are keys to efficient manipulation of these objects. Creative use of these features permits one to minimize the use of loops and to make code simple and readable. Special effort should be made to become familiar with them.

The expression **1:5** (met earlier in for statements) is actually the row vector** [1 2 3 4 5]**. The numbers need not be integers nor the increment one. For example, **0.2:0.2:1.2** gives **[0.2, 0.4, 0.6, 0.8, 1.0, 1.2]**, and **5:-1:1**
gives **[5 4 3 2 1]**. The following statements will, for example, generate a table of sines. Try it.

The number of elements in a vector x is calculated with the function length(x), individual elements are extracted by providing the index k like x(k). This index k must be a number in the range 1 to (including) length(x). The colon operator plays a special role: Used as index, all elements of the vector are returned. Additionally, ranges of numbers can be used as index.

Below we replace the print statement with "ans":

# Working with vectors

Working with vectors is not too different from work with matrices. For example, let us create a vector with values equal 1:

If you want to have all elements to be equal 5, simply multiply this vector by 5: Here we create a vector of size 10 with identical values 5:

If we need to make a vector with 0 values, use **zeros**:

# Example

Calculate

[math] \sum_{k=1}^{k=n}k, \sum_{k=1}^{k=n}k^2, \sum_{k=1}^{k=n}k^3 [/math]

for n=10, n=100, n=10000. The solution is given below: