Matlab – Calculate angle between two vectors matlab

angleMATLABvector

I'm sorry if this question seems a really basic, but I cannot find a good answer online yet.

I'm a little confused with vectors and how to use them in matlab. At the moment I have the following three pair of coordinates (x and y): Person 1, The future location of Person 1 and Person 2. See: The three points in a 2d view

Now I want to calculate the angle between "the vector which goes from person 1 to person 2" and "the vector from person 1 to person 1 future". I've found some matlab functions which could do this with the vectors, but I am not sure I am actually using the right input for each vector.

So now my question is how can I use these coordinates (and the difference between them) to calculate the angle from the image?

Best Answer

Although StefanM's solution is a pretty common solution to this, it is actually computationally expensive, but most importantly, incorrect when the vectors are tiny and/or the angle is near 0 or π -- it can actually result in angles that are slightly negative, or slightly exceed π.

Thus, it gives a false sense of robustness. I'd instead suggest

theta = acos(min(1,max(-1, a(:).' * b(:) / norm(a) / norm(b) )));

More robust, more correct, over 10× faster when run in a loop, and understandable by laymen without documentation, because it still agrees mostly with the "classical" formula.

Related Topic