How can I determine the angle between two vectors in MATLAB?
2,387 views (last 30 days)
More Answers (9)
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.,
An extreme case to clearly show the difference:
>> a = 1e-10 % start with a very small angle
>> u = 4*[1 0 0] % arbitrary non-unit vector in X direction
4 0 0
>> v = 5*[cos(a) sin(a) 0] % vector different from u by small angle
5 5e-10 0
>> acos(dot(u,v)/(norm(u)*norm(v))) % acos formulation does not recover the small angle
>> atan2(norm(cross(u,v)),dot(u,v)) % atan2 formulation does recover the small angle
Boris Povazay on 17 Jun 2018
Just a note on how to vectorize the whole thing: (semicolons purposely omitted to see the intermediate results)
u = [1 2 0];
v = [1 0 0];
ThetaInDegrees = atan2d(NC,D)
uf = repmat(u,5,1)
vf = repmat(v,5,1)
vNC=vecnorm(vC,2,2) % since only z-rotation is allowed anyway, this is equivalent to: vNC=vC(:,3)
vThetaInDegrees = mean(atan2d(vNC,vD))
or in short (the hard to read variant)
VThetaInDegrees =atan2d( vecnorm(cross(Vu,Vv,2),2,2) , dot(Vu,Vv,2) )
theodore panagos on 29 Oct 2018
Coordinates of two vectors xb,yb and xa,ya .
Dhritishman on 3 Jul 2022
Currently, there is no built-in MATLAB function to calculate the angle between two vectors. However, you can use dot product property of two vectors to find the angle:
cosOfAngle = max(min(dot(u,v)/(norm(u)*norm(v)),1),-1);
angleInDegrees = real(acosd(cosOfAngle));
Darko Kulic on 6 Nov 2022
Edited: Darko Kulic on 6 Nov 2022
Hi, i would like to update the answer:
u = [1,1,1]'
v = [2,2,1]'
angle= subspace(u, v)
angle_deg = rad2deg(angle)
The subspace Function was added 2006a.