Is there a faster way to plot wireframe cubes from their centers and sizes?
Show older comments
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
Accepted Answer
More Answers (1)
Christopher Berry
on 6 Aug 2014
If all you need is truly a wireframe cube, then you can speed things up a quite a bit by using only lines and avoiding patches altogether. Like this:
%Scale and transpose
center = [4 4 4];
cubesize = 2;
%Vertices for Line Cube. Order matters
X = [0 0 1 1 0 0 1 1 1 1 1 1 0 0 0 0 0]';
Y = [0 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 0]';
Z = [0 0 0 0 0 1 1 0 1 1 0 1 1 0 1 1 0]';
%Example two cube matrix. Unit cube and one scaled/translated cube
X1 = [X X*cubesize+center(1)];
Y1 = [Y Y*cubesize+center(2)];
Z1 = [Z Z*cubesize+center(3)];
%Single plot command for all 'cube lines'
plot3(X1,Y1,Z1);
1 Comment
Itzik Ben Shabat
on 7 Aug 2014
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!