Pages - Menu

Monday 8 October 2012

Vector operations in MATLAB

In my most recent article I presented you a large list of commands that will ease your work with vectors in MATLAB.

Now, it's time to discuss about some operations that can be performed on vectors.

I will start by defining the following two vectors:
>> vec1=[1 2 3 4]
vec1 =
     1     2     3     4
>> vec2=[4 3 2 1]
vec2 =
     4     3     2     1

To sum two vectors, they must have the same dimension. Summing two vectors means to sum the elements of the two vectors found on the same position. In order to do this, the vectors must have the same dimension.
>> vec1+vec2
ans =
    5    5    5    5

The observations I made on suming two vectors in MATLAB also apply to substraction.
>> vec1-vec2
ans =
    -3    -1    1    3

Since a row vector is a 1xn matrix and a column vector is a nx1, to multiply vectors, the number of rows of the first one must have the same dimension as the number of columns of the second one.
>> vec1*[1;2;3;4]
ans =
    30

Array operations are done element by element. In order to differentiate them from the matrix operations, the . character is used before the arithmetical operator. However, this character it is not used for addition and substraction since they are the same for both matrices and arrays.

To calculate a element by element operation between two vectors, they both must be either a row or column vector with the same length.

For a element by element multiplication, type in: 

>> vec1.*vec2
ans =
    4    6    6    4

The following sequence computes a element by element division:
>> [1;2;3]./[3;2;1]
ans =
    0.3333
    1.0000
    3.0000

An array raise to power can be performed as follows:
>> vec1.^vec2
ans =
    1    8    9    4

The second vector can also be a scalar:
>> vec1.^2
ans =
    1    4    9    16

For a cross product of two vectors, use cross The two vectors must have the size 3. 
>> v1=[1 2 3]
v1 =
    1     2     3
>> v2=[4 5 6]
v2 =
    4     5     6
>> cross(v1,v2)
ans =
   -3     6     -3

For the scalar product of two vectors, use dot.
>> dot(v1,v2)
ans =
   32

My next post will be about MATLAB commands when working with matrices.

No comments:

Post a Comment