VECTORANGLE3D Angle between two 3D vectors. THETA = vectorAngle3d(V1, V2) Computes the angle between the 2 3D vectors V1 and V2. The result THETA is given in radians, between 0 and PI. Example % angle between 2 orthogonal vectors vectorAngle3d([1 0 0], [0 1 0]) ans = 1.5708 % angle between 2 parallel vectors v0 = [3 4 5]; vectorAngle3d(3*v0, 5*v0) ans = 0 See also vectors3d, vectorNorm3d, crossProduct3d
0001 function theta = vectorAngle3d(v1, v2) 0002 %VECTORANGLE3D Angle between two 3D vectors. 0003 % 0004 % THETA = vectorAngle3d(V1, V2) 0005 % Computes the angle between the 2 3D vectors V1 and V2. The result THETA 0006 % is given in radians, between 0 and PI. 0007 % 0008 % 0009 % Example 0010 % % angle between 2 orthogonal vectors 0011 % vectorAngle3d([1 0 0], [0 1 0]) 0012 % ans = 0013 % 1.5708 0014 % 0015 % % angle between 2 parallel vectors 0016 % v0 = [3 4 5]; 0017 % vectorAngle3d(3*v0, 5*v0) 0018 % ans = 0019 % 0 0020 % 0021 % See also 0022 % vectors3d, vectorNorm3d, crossProduct3d 0023 % 0024 0025 % ------ 0026 % Author: David Legland 0027 % E-mail: david.legland@inrae.fr 0028 % Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b) 0029 % Copyright 2010-2024 INRA - Cepia Software Platform 0030 0031 % compute angle using arc-tangent to get better precision for angles near 0032 % zero, see the discussion in: 0033 % http://www.mathworks.com/matlabcentral/newsreader/view_thread/151925#381952 0034 theta = atan2(vectorNorm3d(crossProduct3d(v1, v2)), sum(bsxfun(@times, v1, v2),2)); 0035 0036 % equivalent to: 0037 % v1 = normalizeVector3d(v1); 0038 % v2 = normalizeVector3d(v2); 0039 % theta = acos(dot(v1, v2, 2));