MATLAB Answers

# How to calculate a rotation matrix between two 3d points

483 views (last 30 days)
alessiadele on 20 Feb 2019
Hi everyone!
I have two vectors that represent one point with respect to two different reference systems, eg, p0=[x0, y0, z0] and p1=[x1, y1, z1]; I need to know wich is the rotation matrix that transform the vector p1 to the vector p0. I absolutely don't know the angle rotation, neither the axis around wich the rotation is carried out.
I've tried to use 'vrrotvec' function and then 'vrrotvec2mat' to convert rotation from axis-angle to matrix representation; in theory, if I use this two functions to calculate the rotation matrix R between p1 and p0, when I compute R*p1 I should obtain p0, but the outcome is a vector different from p0.
I hope I've been clear!
Do you have any suggestion?
Thank you!!
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Jos (10584) on 20 Feb 2019
Edited: Jos (10584) on 20 Feb 2019
You can used dot and cross products to get the rotation matrix:
% two random 3D vectors
p0 = randi(10,3,1)
p1 = randi(10,3,1)
% calculate cross and dot products
C = cross(p0, p1) ;
D = dot(p0, p1) ;
NP0 = norm(p0) ; % used for scaling
if ~all(C==0) % check for colinearity
Z = [0 -C(3) C(2); C(3) 0 -C(1); -C(2) C(1) 0] ;
R = (eye(3) + Z + Z^2 * (1-D)/(norm(C)^2)) / NP0^2 ; % rotation matrix
else
R = sign(D) * (norm(p1) / NP0) ; % orientation and scaling
end
% R is the rotation matrix from p0 to p1, so that (except for round-off errors) ...
R * p0 % ... equals p1
inv(R) * p1 % ... equals p0
##### 3 CommentsShowHide 2 older comments
Lucien Robinault on 4 Mar 2021
Hello,
First of all, thanks a lot for this.
Would you have any references on this way of doing by any chances? It is definitly not the way it is explained on all the ressources on rotation matrix (which I couldn't manage to get working anyway), so I would really like to finally understand the process involved in finding the rotation matrix.
Thanks a lot

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!