Leo
Leo

Reputation: 75

calculate the angle between 2 vectors, clockwise and from 0 to 2*pi

I have two (2-D) vectors with a common vertex ( I had made these 2 vectors out of 3 given points ) . I want to find the angle between them, from 0 to 2*pi, and I need it clockwise and positive. I currently use this:

v1=[x1 y1]-[X Y];
v2=[x2 y2]-[X Y];
ang = mod(atan2(v1(1)*v2(2)-v2(1)*v1(2),v1(1)*v2(1)+v1(2)*v2(2)),2*pi);
if ang==0
    Angle=ang; 
else
    Angle=360 - (ang*180/pi);   % change Radian to Degree
end

Although it works correctly, I was wondering if there is any better way to find the angle, maybe not using if/else??!

Thanks in advance

Upvotes: 3

Views: 8572

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

The clockwise angle is the exact opposite from what atan2 assumes, so you just have to negate it:

Angle = mod(-atan2(v1(1)*v2(2)-v1(2)*v2(1), v1*v2'), 2*pi) * 180/pi;

which is, in essence, identical to Bas' answer I see now :)

Upvotes: 1

Bas Swinckels
Bas Swinckels

Reputation: 18488

I assume you want to restrict the output to the half-open interval [0, 360). In that case, simply do the mod at the end, after your other conversions, no if required:

ang = atan2(v1(1)*v2(2)-v2(1)*v1(2),v1(1)*v2(1)+v1(2)*v2(2));
Angle = mod(-180/pi * ang, 360);

Upvotes: 3

Related Questions