Cross product of two vectors(function)

I need to create a function that calculates the cross product of two vectors V1 and V2.
V1 X V2=(Vy1*Vz2 - Vy2*Vz1)i + (Vz1*Vx2 - Vz2*Vx1)j + (Vx1*Vy2 - Vx2*Vy1)k
V1= Vx1i + Vy1j + Vz1k [-2,4,.5]
V2= Vx2i + Vy2j + Vz2k [.5,3,2]
Im completely lost at why i cant get this to work. The function should be something like crossprod[i j k] but i dont know how to implement i j k as inputs, for both vectors. Heres what i tried to do, not using i j k as inputs.
function [result]=cross_product(V1,V2)
%CROSS_PRODUCT calculates the cross product of two vectors.
V1=[v1x,v1y,v1z];
V2=[v2x,v2y,v2z];
i=(v1y*v2z - v2y*v1z);
j=(v1z*v2x - v2z*v1x);
k=(v1x*v2y - v2x*v1y);
result=i+j+k;
end

 Accepted Answer

V1=[v1x,v1y,v1z];
V2=[v2x,v2y,v2z];
Wrong code! you already have V1 and V2 not the other variables.
v1x=V1(1);v1y=V1(2);v1z=V1(3)
v2x=V2(1);v2y=V2(2);v2z=V2(3)
or just forget about those new variables and use only the V1 and V2
function [result]=cross_product(V1,V2)
%CROSS_PRODUCT calculates the cross product of two vectors.
i=(V1(2)*V2(3) - V2(2)*V1(3));
j=(V1(3)*V2(1) - V2(3)*V1(1));
k=(V1(1)*V2(2) - V2(1)*V1(2));
%result=i+j+k; %this is wrong
result=[i,j,k]; %this is right
end

3 Comments

Did you mean result = [i j k]?
The answer should be 6.5000 + 4.2500 + -8.0000 , how would would you implement that without adding them? Also i want to make a error check to make sure each vector has 3 components. is it possible to use nargchk for that inside the function?
I was mislead by Kyle, James thanks for pointing the obvious error

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 10 Apr 2011
OK. I will make a stronger statement this time. i+j+k is the wrong answer. You need to return a 3-vector, and i+j+k is not a 3-vector. Check the above code result against the built-in cross function and you will see what I mean. The above code result is wrong. Then reconsider my advice to return result=[i,j,k].

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!