Transforming Objects Efficiently

Moving objects, for example by rotation, requires transforming the data that defines the objects. You can improve performance by taking advantage of the fact that graphics hardware can apply transforms to the data. You can then avoid sending the transformed data to the renderer. Instead, you send only the four-by-four transform matrix.

To realize the performance benefits of this approach, use the hgtransform function to group the objects that you want to move.

The following examples define a sphere and rotate it using two techniques to compare performance:

  • The rotate function transforms the sphere’s data and sends the data to the renderer thread with each call to drawnow.

  • The hgtransform function sends the transform matrix for the same rotation to the renderer thread.

Code with Poor PerformanceCode with Better Performance

When object data is large, the update bottleneck becomes a limiting factor.

% Using rotate
[x,y,z] = sphere(270);

s = surf(x,y,z,z,'EdgeColor','none');
axis vis3d
for ang = 1:360

Using hgtransform applies the transform on the renderer side of the bottleneck.

% Using hgtransform
ax = axes;
[x,y,z] = sphere(270);

% Transform object contains the surface
grp = hgtransform('Parent',ax);
s = surf(ax,x,y,z,z,'Parent',grp,...

grid on
axis vis3d

% Apply the transform
for ang = linspace(0,2*pi,360)
   tm = makehgtform('axisrotate',[1,1,1],ang);
   grp.Matrix = tm;