我自己编写的函数有问题。我没有找到任何问题如何自己解决,所以我在这里发布它希望有人会看到我没有看到的东西......(这是我的第一个问题,我不知道如何格式化它Matlab代码,我很抱歉)
这是我的函数,它计算光线(由段 CD 给出)在“墙”(由 AB 给出)上的入射角。AB(墙)应该是水平或垂直的,段 CD 和墙 AB 应该有一个交叉点:
function angle = incidentAngle(AB,CD)
%AB and CD are two vectors of size 1x4
%AB = [a1 a2 b1 b2] et CD = [c1 c2 d1 d2]
%AB is a segment from the point (a1,b1) to the point (a2,b2)
if(AB(1)==AB(3)) % The wall is vertical
if(CD(1)==CD(3)) % The "ray" is vertical too, the angle is 90° or pi/2
angle = pi/2;
else
angle = abs(atan((CD(2)-CD(4))/(CD(1)-CD(3))));
end
else
if(AB(2)==AB(4))% The wall is horizontal
if(CD(2)==CD(4)) % The "ray" is horizontal too, the angle is 90° or pi/2
angle = pi/2;
else
angle = abs(atan((CD(1)-CD(3))/(CD(2)-CD(4))));
end
end
end
end
问题(例如)是:
当我将 AB 和 CD 定义为
AB = [0 1 0 5];
CD = [-1 2 3 4];
我做的
angle = incidentAngle(AB,CD)
在命令窗口中,我收到消息错误:
??? Subscript indices must either be real positive integers or logicals.
而且我不明白为什么...
如果现在我只是在命令窗口中复制该函数,如下所示:
AB = [0 1 0 5];
CD = [-1 2 3 4];
angle = 0;
if(AB(1)==AB(3)) % The wall is vertical
if(CD(1)==CD(3)) % The "ray" is vertical too, the angle is 90° or pi/2
angle = pi/2;
else
angle = abs(atan((CD(2)-CD(4))/(CD(1)-CD(3))));
end
else
if(AB(2)==AB(4))% The wall is horizontal
if(CD(2)==CD(4)) % The "ray" is horizontal too, the angle is 90° or pi/2
angle = pi/2;
else
angle = abs(atan((CD(1)-CD(3))/(CD(2)-CD(4))));
end
end
end
angle
我得到正确答案,
angle =
0.4636