MATLAB: How to calculate the angle between two rays (or two vectors)

anglelines

I want to find the angle between two vectors, but some times, it looks not very correct.
Is there any better methods to do this?
Tx = [-1 10];
current = [2 4]; % common point
last = [0 4];
figure;
aa = [Tx;current]
plot(aa(:,1),aa(:,2),'bo-'); hold on;
aa1 = [last;current]
plot(aa1(:,1),aa1(:,2),'mo-'); hold on;
plot(current(1),current(2),'go')
angle = (atan((Tx(2)-current(2))/(Tx(1)-current(1))) - atan((last(2)-current(2))/(last(1)-current(1)))) * 180/pi
axis([-4 10 -4 10])

Best Answer

there is a good explaination for the atan2d() function
If v1 = [x1,y1] and v2 = [x2,y2] are the components of two vectors, then
a = atan2d(x1*y2-y1*x2,x1*x2+y1*y2);
gives the angle in degrees between the vectors as measured in a counterclockwise direction from v1 to v2.
If that angle would exceed 180 degrees, then the angle is measured in the clockwise direction but given a negative value.
In other words, the output of 'atan2d' always ranges from -180 to +180 degrees.
One further observation: Besides the greater range of 'atan2d' as compared with 'acosd', the former does not suffer the inaccuracies that occur with 'acosd' for angles near zero and 180 degrees.