# How can I find the angle between two vectors, including directional information?

1.087 views (last 30 days)
Sebastian Echeverri on 24 Feb 2015
Edited: Cenker Canbulut on 3 Aug 2020
Hello, I am a graduate student, and I am working on a script that tracks the position of animals during a courtship. I have position data in the form of XY coordinates from two points on each animal's body taken from top down filming. I use these two points to create a vector that defines the animal's orientation. My script needs to calculate the angle between these two vectors, but also include directional information - IE, go from -180 through 0 to 180 degrees, depending on where the vectors are placed (see image). This is the code that I currently have. It gives me the desired angle (I believe), but is NOT directional. 60 degrees to either side spits out as 60 degrees no matter which it is.

Roger Stafford on 24 Feb 2015
Edited: Roger Stafford on 24 Feb 2015
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.
Seth Wagenman on 31 Jul 2020
Here is the link to my file developed in response to the same need in the 3-D case:

Yashar Farajpour on 17 Apr 2020
Edited: Yashar Farajpour on 17 Apr 2020
You can use subspace function.
A = [x1,y1,z1];
B = [x2,y2,z2];
Angle = subspace(A',B')
%transposed! they must be column vectors