MATH/CMSC 206 - Introduction to Matlab

Announcements Syllabus Tutorial Projects Submitting

Vectors and Matrices

Contents

Entering Vectors

Matlab allows us to enter vectors very easily. We can do a row vector whereby columns are separated by spaces or commas and rows are separated by semicolons. Try the following for a vertical vector. The semicolons put the numbers on different rows.

v=[1;2;3]
v =

     1
     2
     3

And for a horizontal vector (though we won't use these much). The commas put the numbers on different columns. You could just use spaces instead of commas too.

v=[1,2,3]
v =

     1     2     3

We can also create vectors with variables in them provided we declare the variables symbolically first. For example:

syms t;
v=[t;t^2;t-3]
 
v =
 
     t
   t^2
 t - 3
 

Basic Vector Operations

Matlab deals with vectors very intuitively. For example we can add and subtract vectors using + and - and we can do scalar multiplication simply by multiplying by a constant.

A=[-1;0;3];
B=[5;4;1];
A+B
ans =

     4
     4
     4

A-3.1*B
ans =

  -16.5000
  -12.4000
   -0.1000

We can be more fancy and find things like the dot product, cross product, magnitude (also known as norm) and so on.

dot(A,B)
ans =

    -2

cross(A,B)
ans =

   -12
    16
    -4

norm(A)
ans =

    3.1623

More Subtle Vector Operations

Suppose a and b are vectors like:

a=[1 2 7]
b=[4 3 0]
a =

     1     2     7


b =

     4     3     0

and suppose we wish to multiply each entry in a by the corresponding entry in b. Note that this is neither a dot product nor a cross product. Instead we use the special Matlab notation .*, so a.*b would find [1*4 2*3 7*0]:

a.*b
ans =

     4     6     0

We can do the same with ./ and .^ which will divide or apply powers to corresponding entries:

a./b
a.^b
ans =

    0.2500    0.6667       Inf


ans =

     1     8     1

Entering Matrices

Matrices can also be defined very easily. Rows are separated by semicolons while columns in the vector can be separated either by commas or spaces. For example the following gives a 2 x 3 matrix:

A=[1 2 3;4 5 6]
A =

     1     2     3
     4     5     6

While the following gives a 4 x 2 matrix with variable entries:

syms t;
B=[t 2;t^2 exp(t);t+1 t-1;t 0]
 
B =
 
[     t,      2]
[   t^2, exp(t)]
[ t + 1,  t - 1]
[     t,      0]
 

Basic Matrix Operations

Try the following commands and check out what they do. You should be able to figure them out. We've suppressed the output so as to not give it away!

A=[1 2 3;4 5 6];
B=[-1 0 2;6 7 2];
C=[t 2;t^2 exp(t);t+1 t-1;t 0];

Then:

A+3*B;
C*A;
A+5;
A.*B;

Self-Test

  1. Write the Matlab command which will create a 4 x 3 matrix such that the entry in row i and column j will be 2^(i-3j).
  2. Write down a series of Matlab commands which will define t symbolically and then find the product of the matrices [1 t -t;2 t^2 1/t] and [t 1/t^2;t 2;-1 0].

Answers to Self-Test

Next Topic:   More with Vectors and Matrices