Cross
Product  coded in a numerical software
In this example, we are going to write a function to find the cross product of two
given vectors u
and v.
If u
= [u1 u2 u3] and v
= [v1 v2 v3],
we know that the product w
is defined as w
= [(u2v3 – u3v2)
(u3v1  u1v3)
(u1v2  u2v1)].
We can check the function by taking cross products of unit vectors i
= [1 0 0], j
= [0 1 0], and k
= [0 0 1]
First, we create the function in an mfile as follows:
function w = crossprod(u,v)
% We're
assuming that both u and v are 3D vectors.
% Naturally,
w = [w(1) w(2) w(3)]
w(1) = u(2)*v(3)  u(3)*v(2);
w(2) = u(3)*v(1)  u(1)*v(3);
w(3) = u(1)*v(2)  u(2)*v(1);
Then, we can call the function from any script, as follows in
this example:
% Clear
screen, clear previous variables and closes all figures
clc; close all; clear
% Supress
empty lines in the output
format compact
% Define unit
vectors
i = [1 0 0];
j = [0 1 0];
k = [0 0 1];
% Call the
previously created function
w1 = crossprod(i,j)
w2 = crossprod(i,k)
disp('*** compare with results by Matlab ***')
w3 = cross(i,j)
w4 = cross(i,k)
And Matlab displays:
w1 =
0
0 1
w2 =
0
1 0
*** compare with results by Matlab ***
w3 =
0
0 1
w4 =
0
1 0
>>
From
'Cross Product' to
home
From
'Cross
Product' to 'Matlab Examples'

