Vectors
Contents
Entering vectors in MATLAB
A vector in three space is represented in MATLAB as a 1 x 3 array (an array with with one row, three columns). So, to enter the vectors a = -3 i - 4 j- k, b = 6 i + 2 j + 3 k and u = x i + y j + z k you type
a = [-3, -4, -1]
a = -3 -4 -1
b = [6, 2, 3]
b = 6 2 3
and
syms x y z u = [x, y, z]
u = [ x, y, z]
The command syms is necessary to tell MATLAB that x,y,z are symbolic. If you forget to do that, you will get an error message telling you that you have an undefined function or variable.
Comments on style
When you publish your Mfile, MATLAB will list all the commands in a cell together, followed by all the output. You create a new cell by starting a line with %%. Make frequent use of these.
A line beginning with % indicates a comment. To have the comments look nice in the published file, precede them with %%. Otherwise, they come out as lines starting with %, as this shows:
x^2
% Here's a comment.
ans = x^2
Vector arithmetic
You can add and subtract these and multiply them by scalars.
a + b
ans = 3 -2 2
5*a
ans = -15 -20 -5
Dot product
You can calculate the dot product of two vectors with the command dot.
dot(a,b)
ans = -29
dot(a,u)
ans = - 3*x - 4*y - z
dot(u,a)
ans = - 3*conj(x) - 4*conj(y) - conj(z)
This isn't the same as dot(a,u). MATLAB doesn't know that x, y and z are real. It assumes they are complex. It takes the complex conjugate of the components of the first vector. The complex conjugate of the complex number c+di is c-di where i is the square root of -1. So the complex conjugate of 3+7i is 3-7i. Since we are only dealing with real vectors, you can get around this problem by defining a function realdot
realdot = @(u,v) u*transpose(v)
realdot = @(u,v)u*transpose(v)
realdot(u,a)
ans = - 3*x - 4*y - z
or if you downloaded the Mfiles, you can just give the command realdot.
Or you could tell MATLAB the variables are real by giving the command
syms x y z real dot(u,a)
ans = - 3*x - 4*y - z
Cross product
You can calculate the cross product of two vectors with the command cross.
cross(a,b)
ans = -10 3 18
cross(b,a)
ans = 10 -3 -18
cross(a,u)
ans = [ y - 4*z, 3*z - x, 4*x - 3*y]