Angle between two vectors matlab
22,179
Solution 1
Based on this link, this seems to be the most stable solution:
atan2(norm(cross(a,b)), dot(a,b))
Solution 2
There are a lot of options:
a1 = atan2(norm(cross(v1,v2)), dot(v1,v2))
a2 = acos(dot(v1, v2) / (norm(v1) * norm(v2)))
a3 = acos(dot(v1 / norm(v1), v2 / norm(v2)))
a4 = subspace(v1,v2)
All formulas from this mathworks thread. It is said that a3 is the most stable, but I don't know why.
For multiple vectors stored on the columns of a matrix, one can calculate the angles using this code:
% Calculate the angle between V (d,N) and v1 (d,1)
% d = dimensions. N = number of vectors
% atan2(norm(cross(V,v2)), dot(V,v2))
c = bsxfun(@cross,V,v2);
d = sum(bsxfun(@times,V,v2),1);%dot
angles = atan2(sqrt(sum(c.^2,1)),d)*180/pi;
Author by
Jack_111
Updated on July 09, 2022Comments
-
Jack_111 almost 2 years
I want to calculate the angle between 2 vectors
V = [Vx Vy Vz]
andB = [Bx By Bz]
. is this formula correct?VdotB = (Vx*Bx + Vy*By + Vz*Bz) Angle = acosd (VdotB / norm(V)*norm(B))
and is there any other way to calculate it?
My question is not for normalizing the vectors or make it easier. I am asking about how to get the angle between this two vectors
-
Dennis Jaheruddin over 10 yearsIf you want to be concise at least recommend
V*B'
-
High Performance Mark over 10 yearsIs there some reason you have avoided the intrinsic
dot
function ? -
Marc Claesen over 10 years@HighPerformanceMark Not apart from forgetting its existence.
-
Jack_111 over 10 yearsno there is no reason and the dot function works very well but just I wrote the question like this.
-
Jack_111 over 10 yearsThat's why I am confused and I don't know which one is the correct one and why
-
Dennis Jaheruddin over 10 yearsJust read more via the link I provided. They are both correct in theory, but in practice this one is mentioned to provide more stable results (whilst the alternative with
acos
computes a bit faster).