GEOSC 444
Matlab Application for Geoscience

Lesson 2: column vectors, vector math

PrintPrint

Syntax introduced:

' .* mode sum :

Make a column vector

A column vector is created inside square brackets with semicolons or returns separating elements. You can turn a row vector into a column vector (or the other way around) with the transpose operator, which is a single quote mark '.

>> x=[2 4 6 8 10];
>> y=[1;3;5;7;9];
>> x

x =

     2     4     6     8    10

>> y

y =

     1
     3
     5
     7
     9

Vector arithmetic

Who cares whether a vector is a row vector or a column vector, you say? Well, if all of your vectors are of the same type and the same length then adding one to the other and subtracting one from the other of them works piece by piece:

>> x+x

ans =

     4     8    12    16    20

>> y+y

ans =

     2
     6
    10
    14
    18

But adding and subtracting when one vector is a row vector and the other one is a column vector doesn't work piece by piece:

>> M=x+y

M =

     3     5     7     9    11
     5     7     9    11    13
     7     9    11    13    15
     9    11    13    15    17
    11    13    15    17    19

What did MATLAB do here? It constructed a 5x5 matrix M in the following way. The first row of M is x(1)+y(1), x(2)+y(1), x(3)+y(1), x(4)+y(1), x(5)+y(1). The second row of M is x(1)+y(2), x(2)+y(2), x(3)+y(2), x(4)+y(2), x(5)+y(2). And so forth. The number of columns of one vector have to equal the number of rows of the other vector for this to work.

Dot products and cross products

You can also multiply and divide two vectors piece by piece, but you have to tell MATLAB you want to do it that way by using the dot product .*:

>> x.*x

ans =

     4    16    36    64   100

>> y.*y

ans =

     1
     9
    25
    49
    81

You'll get an error message if you try to multiply x by x by merely writing x*x. However, you can multiply x by y by just typing x*y since one of them is a column vector and the other is a row vector and the number of columns of x equals the number of rows in y. Try it! You get

>> x*y

ans =

   190

Why? Because you are basically asking MATLAB to take the cross product of two orthogonal vectors, so the answer is a scalar. The actual calculation is equivalent to:

>> x(1)*y(1)+x(2)*y(2)+x(3)*y(3)+x(4)*y(4)+x(5)*y(5)

ans =

   190

Check yourself!