MATLAB: Loosing quadrant data using atan2 when finding angle between 3 points (in 3D space) in MATLAB

3danglesMATLAB

I want to find the angle between O-F1 and O-Tp. Tp is a point that can vary depending on different inputs. So in the attached diagram I have shown 2 points Tp1 and Tp2. As indicated in the attached figure, the angle output by my code gives me an angle in the range of 0 to 180. However I want the range to be in the form of 0 to 360 or -180 to 180.
Some additional info: the 3 points (O, F1, Tp) lie on a plane formed by three other points(F1, F2 and F3) forming an equilateral triangle. F1 is the chosen reference point for measurement of the angle in clockwise direction. O is the centroid of the triangle.
I have tried several alternate equations and thought of using spherical/cylindrical coordinates. Haven't tried looking up quaternions yet. But I don't think this is supposed to be difficult. I feel I am messing something up.
%calculating unit vectors
v1 = OF1/norm(OF1);
v2 = OTp/norm(OTp);
%Angle Calculation
A = rad2deg(atan2(norm(cross(v1,v2)), dot(v1,v2)))
Picture – 1 = [diagram showing how the output to my code is giving the same angle for different points instead of showing one of them as -173 degrees or -187 degrees]

Best Answer

You diagram looks like 2D and not 3D.
In 3D you can turn around and look in opposite direction. The atan2 formula assume you look from the cross vector direction and thus the angle is always > 0.
If you have a preference direction (for example vector normal and come out of your drawing plane) you need to take the dot product of the cross-vector and this normal vector and reverse the sign.
d = [0;0,1] % your preference direction
x = cross(v1,v2);
nx = norm(x);
A = atan2(nx, dot(v1,v2));
x = x / nx;
if dot(x,d) < 0
x = -x;
A = -A;
end
% v2 is obtained by rotating v1 about the (unit) x vector of angle A radian