MATLAB 画立方体的几种方法

方法1:

function plotcube(varargin)
% PLOTCUBE - Display a 3D-cube in the current axes
%
%   PLOTCUBE(EDGES,ORIGIN,ALPHA,COLOR) displays a 3D-cube in the current axes
%   with the following properties:
%   * EDGES : 3-elements vector that defines the length of cube edges
%   * ORIGIN: 3-elements vector that defines the start point of the cube
%   * ALPHA : scalar that defines the transparency of the cube faces (from 0
%             to 1)
%   * COLOR : 3-elements vector that defines the faces color of the cube
%
% Example:
%   >> plotcube([5 5 5],[ 2  2  2],.8,[1 0 0]);
%   >> plotcube([5 5 5],[10 10 10],.8,[0 1 0]);
%   >> plotcube([5 5 5],[20 20 20],.8,[0 0 1]);

% Default input arguments
inArgs = { ...
  [10 56 100] , ... % Default edge sizes (x,y and z)
  [10 10  10] , ... % Default coordinates of the origin point of the cube
  .7          , ... % Default alpha value for the cube's faces
  [1 0 0]       ... % Default Color for the cube
  };

% Replace default input arguments by input values
inArgs(1:nargin) = varargin;

% Create all variables
[edges,origin,alpha,clr] = deal(inArgs{:});

XYZ = { ...
  [0 0 0 0]  [0 0 1 1]  [0 1 1 0] ; ...
  [1 1 1 1]  [0 0 1 1]  [0 1 1 0] ; ...
  [0 1 1 0]  [0 0 0 0]  [0 0 1 1] ; ...
  [0 1 1 0]  [1 1 1 1]  [0 0 1 1] ; ...
  [0 1 1 0]  [0 0 1 1]  [0 0 0 0] ; ...
  [0 1 1 0]  [0 0 1 1]  [1 1 1 1]   ...
  };

XYZ = mat2cell(...
  cellfun( @(x,y,z) x*y+z , ...
    XYZ , ...
    repmat(mat2cell(edges,1,[1 1 1]),6,1) , ...
    repmat(mat2cell(origin,1,[1 1 1]),6,1) , ...
    'UniformOutput',false), ...
  6,[1 1 1]);


cellfun(@patch,XYZ{1},XYZ{2},XYZ{3},...
  repmat({clr},6,1),...
  repmat({'FaceAlpha'},6,1),...
  repmat({alpha},6,1)...
  );

view(3);

测试代码

plotcube([5 5 5],[ 2  2  2],.8,[1 0 0]);
plotcube([5 5 5],[10 10 10],.8,[0 1 0]);
plotcube([5 5 5],[20 20 20],.8,[0 0 1]);

效果:


这里写图片描述

方法2:

使用patch函数。
语法:

patch(x, y)
patch(x, y, [r g b])
patch(X,Y,Z,C) 
patch('Faces',F,'Vertices',V)

patch(‘Faces’,F,’Vertices’,V) 创建一个或多个多边形,其中 V 指定顶点的值,F 定义要连接的顶点。当有多个多边形时,仅指定唯一顶点及其连接矩阵可以减小数据大小。为 V 中的每个行指定一个顶点。要创建一个多边形,请将 F 指定为矢量。要创建多个多边形,请将 F 指定为矩阵,其中一行对应于一个多边形。不要求每个面都具有相同的顶点数。要指定不同数量的顶点,请以 NaN 值填充 F。
实例:

clc
clear
format compact
h(1) = axes('Position',[0.2 0.2 0.6 0.6]);
vert = [1 1 1; 1 2 1; 2 2 1; 2 1 1 ; ...
    1 1 2;1 2 2; 2 2 2;2 1 2];
fac = [1 2 3 4; ...
    2 6 7 3; ...
    4 3 7 8; ...
    1 5 8 4; ...
    1 2 6 5; ...
    5 6 7 8];
patch('Faces',fac,'Vertices',vert,'FaceColor','r');  % patch function
material shiny;
alpha('color');
alphamap('rampdown');
view(30,30);

hold on;
vert2 = [1 1 1; 1 2 1; 2 2 1; 2 1 1 ; ...
    1 1 2;1 2 2; 2 2 2;2 1 2]/5;
fac2 = [1 2 3 4; ...
    2 6 7 3; ...
    4 3 7 8; ...
    1 5 8 4; ...
    1 2 6 5; ...
    5 6 7 8];
patch('Faces',fac2,'Vertices',vert2,'FaceColor','b');  % patch function

效果:


这里写图片描述

猜你喜欢

转载自blog.csdn.net/wokaowokaowokao12345/article/details/79519903
今日推荐