How to Use MATLAB to Plot 3D Cubes

Goals

In order to present 3-D matrix data, sometimes it is better to draw some cubes with specified dimensions. But the plot functions in MATLAB cannot directly fulfil this goal. Here is one proper solution based on the integrated function patch in MATLAB.

The control file

The control file is used to call the cube_plot.m function. You may define the origin point and the dimension for the cube. You may also plot more cubes to present 3-dimension data.

clf;
figure(1);
% Use hold on and hold off to plot multiple cubes
hold on;
% Call the function to plot a cube with dimension of X, Y, Z, at point [x,y,z].
cube_plot([1,1,1],1,1,1,'r');
% Figure configurations
% Define the range of x-axis, y-axis, and z-axis in form of
% [xmin,xmax,ymin,ymax,zmin,zmax].
% axis([0,1,0,1,0,1]);
% Set the axis with equal unit.
axis equal;
% Show grids on the plot
grid on;
% Set the lable and the font size
xlabel('X','FontSize',18);
ylabel('Y','FontSize',18)
zlabel('Z','FontSize',18)
% Control the ticks on the axises
h = gca; % Get the handle of the figure
% h.XTick = 0:0.5:1;
% h.YTick = 0:0.5:1;
% h.ZTick = 0:0.5:1;
% Set the color as transparient
material metal
alpha('color');
alphamap('rampup');
% Set the view point
view(30,30);
hold off;
% plot the figure in the form of eps with 600 ppi named 'filename'
% print(gcf,'-depsc2','-r600','filename.eps')

The cube_plot.m function

Save the following code as cube_plot.m

function cube_plot(origin,X,Y,Z,color)
% CUBE_PLOT plots a cube with dimension of X, Y, Z.
%
% INPUTS:
% origin = set origin point for the cube in the form of [x,y,z].
% X = cube length along x direction.
% Y = cube length along y direction.
% Z = cube length along z direction.
% color = STRING, the color patched for the cube.
% List of colors
% b blue
% g green
% r red
% c cyan
% m magenta
% y yellow
% k black
% w white
% OUPUTS:
% Plot a figure in the form of cubics.
%
% EXAMPLES
% cube_plot(2,3,4,'red')
%

% ------------------------------Code Starts Here------------------------------ %
% Define the vertexes of the unit cubic

ver = [1 1 0;
0 1 0;
0 1 1;
1 1 1;
0 0 1;
1 0 1;
1 0 0;
0 0 0];

% Define the faces of the unit cubic
fac = [1 2 3 4;
4 3 5 6;
6 7 8 5;
1 2 8 7;
6 7 1 4;
2 3 5 8];

cube = [ver(:,1)*X+origin(1),ver(:,2)*Y+origin(2),ver(:,3)*Z+origin(3)];
patch('Faces',fac,'Vertices',cube,'FaceColor',color);
end
% ------------------------------Code Ends Here-------------------------------- %

That is it.
Cheers!