I've a problem with a function that I've written by myself. I've not found in any question how to solve it by myself so I post it here hoping that someone's going to see what I didn't see... (It's my first question and I don't know how to format it in Matlab code, I'm sorry about it)
Here is my function, which calculates the incident angle of a ray (given by the segment CD) on a 'wall' (given by AB). AB (the wall) is supposed to be horizontal or vertical and segment CD and wall AB are supposed to have an intersection :
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
The problem (for example) is that :
when I define AB and CD as
AB = [0 1 0 5];
CD = [-1 2 3 4];
and that I do
angle = incidentAngle(AB,CD)
in the command window, I get the message error :
??? Subscript indices must either be real positive integers or logicals.
And I don't understand why...
If now I just copy the function in the command window, like this :
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
I get the right answer,
angle =
0.4636