Cross product of two vectors(function)

조회 수: 28 (최근 30일)
Kyle
Kyle 2011년 4월 9일
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

채택된 답변

Paulo Silva
Paulo Silva 2011년 4월 9일
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
Kyle
Kyle 2011년 4월 9일
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?
Paulo Silva
Paulo Silva 2011년 4월 10일
I was mislead by Kyle, James thanks for pointing the obvious error

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

James Tursa
James Tursa 2011년 4월 10일
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].
  댓글 수: 1
Paulo Silva
Paulo Silva 2011년 4월 10일
I fixed my answer, thanks.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by