MATLAB: Is there a faster way to plot wireframe cubes from their centers and sizes

facevefor looppatch

Hi, so i wrote the attached function.
I will be working with many cubes so i was wondering if there is a better implementation than this one? (i know that the for loop is slower than working with vectors directly but just couldnt figure out a way to implement this better) thanks
function [ model_handle ] = WireCubes( center,cubesize )
%WireCubes plots cubic wireframe according to the cube cener and its size
%INPUT:
%size: nX1 vector containing the size of each cubic element
%centers: nX3 matrix containing the x,y,z coordinates of the cubes
%OUTPUT:
%model_handle: an object handle to the plotted model
NumberOfCubes=size(center,1);
verticesTemplate=[0 0 0;
0 1 0;
1 1 0;
1 0 0;
0 0 1;
0 1 1;
1 1 1;
1 0 1];
facesTemplate=[1 2 3 4;
5 6 7 8;
3 4 8 7;
1 2 6 5;
2 3 7 6;
1 4 8 5];
FV.faces=zeros(NumberOfCubes*6,4);
FV.vertices=zeros(NumberOfCubes*8,3);
faceindex=1;
vertexindex=1;
for i=1:NumberOfCubes
verts = (verticesTemplate-0.5).*cubesize(i,1)+repmat(center(i,:),8,1);
faces=facesTemplate+(i-1)*8;
FV.vertices(vertexindex:vertexindex+7,1:3)=verts;
FV.faces(faceindex:faceindex+5,1:4)=faces;
vertexindex=vertexindex+8;
faceindex=faceindex+6;
end
model_handle=patch(FV,'edgecolor','r','facecolor','none');
end

Best Answer

To do this quickly and to show you what you could do I didn't completely optimize this.
X = repmat(verticesTemplate-.5,NumberOfCubes,1);
Y = repmat(reshape(repmat(cubesize',8,1),[],1),1,3);
Z = reshape(reshape(repmat(center',8,1),[],1),3,[])';
f = repmat(facesTemplate,NumberOfCubes,1)+8*repmat(reshape(repmat([0:NumberOfCubes-1]',1,6)',[],1),1,4);
FV.vertices = X.*Y+Z;
FV.faces = f;
This can substitute the for loop. If you take a look at what i was doing with X,Y, Z, and f it is building the specific cube corners and faces as you're doing but using repmat. The complicated reshape and transposes can most likely be simplified or optimized. for me the above code is 2% to 5% of the time it takes for the for loop.