Apply Rotation Matrix to a Set of Points

15 views (last 30 days)
Hi all,
I have a set of 3D points (3 by N) to which I am applying a rotation (3 by 3) and translation (1 by 3). I can't figure out a way to get it out of a for-loop, and as you can guess, for loops are too slow.
I currently have:
for i=1:N
rotPoints(:,i) = rotationMatrix*points(:,i)+translationVector;
end
giving me what I want. Tried using bsxfun() with it but no success.
Cheers guys, Andrew

Accepted Answer

Matt J
Matt J on 6 Oct 2012
Edited: Matt J on 6 Oct 2012
Two options:
(1) Loop over rows instead of columns (a much shorter loop)
rotPoints=rotationMatrix*points;
for i=1:3
rotPoints(i,:) = rotPoints(i,:)+translationVector(i);
end
(2) using BSXFUN
rotPoints=bsxfun(@plus, rotationMatrix*points, translationVector);
Hard to say which will be faster...
  2 Comments
AndrewL
AndrewL on 6 Oct 2012
Timed it for my problem, which is for a transform of 640x480 points (307200 operations off the top of my head). 1st method took 0.027217 seconds, 2nd method took 0.025025 seconds.
So 1st is marginally faster in this case. I imagine this could be different for much larger operations though.
Cheers by the way
Matt J
Matt J on 6 Oct 2012
marginally slower, I think you mean. Your timings say that the 1st method took longer.

Sign in to comment.

More Answers (1)

Zihe Gao
Zihe Gao on 27 Jul 2018
Edited: Matt J on 27 Jul 2018
No need to use for loop.
translationMat = repmat(traslationVector,N,1);
rotPoints = rotationMatrix*points+translationMat;
  3 Comments
Matt J
Matt J on 27 Jul 2018
Even in R2018a, I still see for-loops showing competitive speed for certain data sizes
N=1e6;
A=rand(3,N);
b=rand(3,1);
tic;
for i=1:3
A(i,:)=A(i,:)+b(i);
end
toc
%Elapsed time is 0.014138 seconds.
tic;
A=bsxfun(@plus, A,b);
toc;
%Elapsed time is 0.008340 seconds.
tic;
A=A+b;
toc;
%Elapsed time is 0.011921 seconds.
tic;
A=A+repmat(b,1,N);
toc;
%Elapsed time is 0.019553 seconds.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!