Vectorized rotate() slower than loop?

2 views (last 30 days)
Chris Sullivan
Chris Sullivan on 26 Mar 2014
Edited: Matt J on 26 Mar 2014
Hi all,
I have an array of patch objects in a scene. I'd like to rotate each object about the z-axis, by some arbitrary angle (different for each patch), about some arbitrary origin (again different for each).
Of course, looping through rotate(handle, axis, angle, origin) is slower than I'd like. So I've been trying to vectorize the operation. But my speed tests seem to suggest this makes things slower! I'm thinking I might not be correctly vectorizing the angle/origin somehow. Anyway, here's my speed test:
% Grab the first 10 patch objects and rotate
c = patch_handles(1:10);
tic
for i=1e3 % Do this 1,000 times
for j=1:10 % Rotate each patch separately
rotate(c(j),[0 0 1],rand,rand(1,3));
end
end
toc
d = patch_handles(1:10);
tic
for i=1:1e3 % Do this 1,000 times
% Rotate all 10 patches at once
rotate(d,[0 0 1],rand(10,1), rand(10,3));
end
toc
......
Result:
Elapsed time is 0.130681 seconds.
Elapsed time is 2.099411 seconds.

Answers (3)

Matt J
Matt J on 26 Mar 2014
Edited: Matt J on 26 Mar 2014
Your comparison is corrupted because the first implementation is only looping over a single value i=1e3 whereas your second version loops over a thousand values 1:1e3.
If you have lots of patches to do, you should probably also set the figure invisible until all patches are rotated. Otherwise, a re-rendering of the entire figure will be done after each rotation.

Chris Sullivan
Chris Sullivan on 26 Mar 2014
Well that was dumb of me. Anyway, even when the iterator is fixed, the vectorized solution is still consistently slower, but they're both in the ~2sec range.
Digging into rotate.m, it seems that the origin is called out specifically as a 3-element vector, so it cannot handle an array of origins. Even if you create a new function and change that, there's still a few other things that would need to be changed in the function to make vectorization of the kind I'm hoping for possible.
But even then, rotate.m is simply looping through the handles, so there's no real vector leveraging.

Matt J
Matt J on 26 Mar 2014
Edited: Matt J on 26 Mar 2014
You could also try this FEX file,
If you extract all of your vertex coordinates for all the patches into a common matrix 3xN matrix XYZ_old, you can then use Syntax 3 of the above file. This will rotate all of the coordinates in a vectorized way. Then you build new patches out of the new coordinates.

Community Treasure Hunt

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

Start Hunting!