Help with function main and writing cross product function

조회 수: 9 (최근 30일)
CalamityGoat
CalamityGoat 2015년 4월 27일
댓글: CalamityGoat 2015년 4월 27일
So I am trying to write a function to calculate the cross product of any two vectors. I am trying to write the code to work with some test vectors I have defined both vectors as 2 dimensional for my test but in eventuality I will want the code to accept either 2 dimensional or 3 dimensional vectors. So far I have:
function main
% vectors a = 3i + 11j; b = 14i - 7.3j;
a = [3 11]; b = [14 -7.3];
vec_c = crosspro(a, b)
end
function w = crosspro(u, v)
% crosspro calculates the crossproduct of u cross v
if length(u) == 2
u = [u 0 ];
end
if length(v) == 2
v = [v 0 ];
end
i = (u(2)*v(3)-u(3)*v(2));
j = (u(3)*v(1)-u(1)*v(3));
k = (u(1)*v(2)-u(2)*v(1));
result=[i j k];
end
I get an error if length(u) == 2, I was given them as a hint based on the code I had previously. Also it says output "w" (and maybe others) are not assigned during call main>crosspro.
Can someone help explain what is going on here and also how to fix my code to work from here? Thanks a bunch!

채택된 답변

Michael Haderlein
Michael Haderlein 2015년 4월 27일
You have to decide if you want to name the output argument "w" or "result". If you change your second last line to
w=[i j k];
things will work. Just as a comment, if you want to make sure that also column vectors work, replace
u=[u 0];
with
u(3)=0;
The same with v of course. Also, I guess this is for educational purpose only - you know the function "cross", don't you?
  댓글 수: 1
CalamityGoat
CalamityGoat 2015년 4월 27일
Excellent! That worked perfectly, it makes sense that I should have named result w. I think I was trying to make result work like I remember return; working in c++. In either case thanks for the help and explanation.
Also I do know of the cross function but thank you for mentioning it as well.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by