# How can I determine the angle between two vectors in MATLAB?

1.768 views (last 30 days)
MathWorks Support Team on 22 Jun 2011
Commented: Bruno Luong on 3 Dec 2022
How can I determine the angle between two vectors in MATLAB?
I have two vectors. Is there a MATLAB function that can determine the angle between them?

MathWorks Support Team on 27 May 2020
Edited: MathWorks Support Team on 27 May 2020
There is no in-built MATLAB function to find the angle between two vectors. As a workaround, you can try the following:
CosTheta = max(min(dot(u,v)/(norm(u)*norm(v)),1),-1);
ThetaInDegrees = real(acosd(CosTheta));
Akihumi on 27 May 2020
Hi, did you miss out a bracket for the min? I got an error and only resolve it with the following code instead.
CosTheta = max(min(dot(u,v)/(norm(u)*norm(v)),1),-1);
ThetaInDegrees = real(acosd(CosTheta));

Pierre-Pascal on 11 Jan 2016
So why doesn't matlab give us a function for that instead of having us look endlessly on forums?

James Tursa on 9 Jul 2015
Edited: James Tursa on 5 Jan 2019
This topic has been discussed many times on the Newsgroup forum ... if I looked hard enough I'm sure I could find several Roger Stafford posts from many years ago on this. E.g., here is one of them:
The basic acos formula is known to be inaccurate for small angles. A more robust method is to use both the sin and cos of the angle via the cross and dot functions. E.g.,
atan2(norm(cross(u,v)),dot(u,v));
An extreme case to clearly show the difference:
a =
1e-10
>> u = 4*[1 0 0] % arbitrary non-unit vector in X direction
u =
4 0 0
>> v = 5*[cos(a) sin(a) 0] % vector different from u by small angle
v =
5 5e-10 0
>> acos(dot(u,v)/(norm(u)*norm(v))) % acos formulation does not recover the small angle
ans =
0
>> atan2(norm(cross(u,v)),dot(u,v)) % atan2 formulation does recover the small angle
ans =
1e-10
Bruno Luong on 3 Dec 2022
@Felix Fischer If you want to find angles of multiple vector pairs put in matrix, use vecnorm rather than norm.

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R13SP1

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by