CREATEROTATIONVECTOR3D Calculates the rotation between two vectors. ROT = createRotationVector3d(A, B) returns the 4x4 rotation matrix ROT to transform vector A in the same direction as vector B. Example A=[ .1 .2 .3]; B=-1+2.*rand(1,3); ROT = createRotationVector3d(A,B); C = transformVector3d(A,ROT); figure('color','w'); hold on; view(3) O=[0 0 0]; drawVector3d(O, A,'r'); drawVector3d(O, B,'g'); drawVector3d(O, C,'r'); See also transformPoint3d, createRotationOx, createRotationOy, createRotationOz Source https://math.stackexchange.com/a/897677 --------- Author: oqilipo Created: 2017-08-07 Copyright 2017
0001 function ROT = createRotationVector3d(A,B) 0002 %CREATEROTATIONVECTOR3D Calculates the rotation between two vectors. 0003 % 0004 % ROT = createRotationVector3d(A, B) returns the 4x4 rotation matrix ROT 0005 % to transform vector A in the same direction as vector B. 0006 % 0007 % Example 0008 % A=[ .1 .2 .3]; 0009 % B=-1+2.*rand(1,3); 0010 % ROT = createRotationVector3d(A,B); 0011 % C = transformVector3d(A,ROT); 0012 % figure('color','w'); hold on; view(3) 0013 % O=[0 0 0]; 0014 % drawVector3d(O, A,'r'); 0015 % drawVector3d(O, B,'g'); 0016 % drawVector3d(O, C,'r'); 0017 % 0018 % See also 0019 % transformPoint3d, createRotationOx, createRotationOy, createRotationOz 0020 % 0021 % Source 0022 % https://math.stackexchange.com/a/897677 0023 % 0024 % --------- 0025 % Author: oqilipo 0026 % Created: 2017-08-07 0027 % Copyright 2017 0028 0029 if isParallel3d(A,B) 0030 if A*B'>0 0031 ROT = eye(4); 0032 else 0033 ROT = -1*eye(4); ROT(end)=1; 0034 end 0035 else 0036 a=normalizeVector3d(A); 0037 b=normalizeVector3d(B); 0038 a=reshape(a,3,1); 0039 b=reshape(b,3,1); 0040 0041 v = cross(a,b); 0042 ssc = [0 -v(3) v(2); v(3) 0 -v(1); -v(2) v(1) 0]; 0043 ROT = eye(3) + ssc + ssc^2*(1-dot(a,b))/(norm(v))^2; 0044 0045 ROT = [ROT, [0;0;0]; 0 0 0 1]; 0046 end 0047 0048 end