How to compute directional angle between two 2D vectors in MatLab?

允我心安 提交于 2019-12-06 16:12:11

To start with, an easier way to think about the angle between two 2D vectors with coordinates is to align an axis with your coordinate vectors and think about the relationship between two vectors. Using the drawing below, we can see that a relative angle can be found by subtracting one angle from the other.

Source: http://almaer.com/blog/uploads/atan2.png

It is not too hard to figure out looking at this graph that we can say

angle = atan2d(y2,x2) - atan2d(y1,x1)

However, since neither of your vectors are known to be aligned along the coordinate axis, the case can arise where the difference above is not in the range (-180, 180). This means we need to code in a check to add or subtract 360 degrees to get our desired angle:

if abs(angle) > 180
  angle = angle - 360*sign(angle)
end

Note, you are using a kind of reverse notation (CW positive) so the final code would look like:

v1 = p1 - p2;
x1 = v1(1);
y1 = v1(2);
v2 = p3 - p1;
x2 = v2(1);
y2 = v2(2);
angle = atan2d(y1,x1) - atan2d(y2,x2)

if abs(angle) > 180
    angle = angle - 360*sign(angle)
end

Where v1 and v2 have been changed to match your drawing.

Like some of the comments mentioned, I'm a little confused about whether you want to use v2=p1-p3 or v2=p3-p1. Regardless, this method will work with any two vectors v and u where u is the reference vector (the vector we are measuring the angle against).

vx = v(1); vy= v(2); ux = u(1); uy = u(2);
va = -atan2d(vy,vx);         % angle of v relative to x-axis (clockwise = +ve)
ua = -atan2d(uy,ux);         % angle of u relative to x-axis (clockwise = +ve)
A = va - ua;                             % angle va relative to ua
A = A - 360*(A > 180) + 360*(A < -180)   % correction put in [-180,180]

This assumes you want the direction clockwise of u to be taken as the positive direction. Otherwise you just flip the sign of A.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!