Skip to content
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));
So why doesn't matlab give us a function for that instead of having us look endlessly on forums?
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: >> v = 5*[cos(a) sin(a) 0] >> acos(dot(u,v)/(norm(u)*norm(v))) >> atan2(norm(cross(u,v)),dot(u,v))
Edited: Gabor Bekes on 15 Sep 2016
This does the same thing, also capable of determining the angle of higher (than one) dimensional subspaces. subspace(vector1,vector2)
Just a note on how to vectorize the whole thing: (semicolons purposely omitted to see the intermediate results) ThetaInDegrees = atan2d(NC,D) 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) )
Coordinates of two vectors xb,yb and xa,ya . angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2))) +pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb)) +sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya))) -sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))
Edited: Mahaveer Singh on 4 May 2021
function angle_in_degrees = vector2angle(u,v) a= sqrt(u(1)^2+u(2)^2+u(3)^2); b=sqrt(v(1)^2+v(2)^2+v(3)^2); angle_in_degrees=acos(c/(a*b))*180/pi
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)); |