我有多个矩形角的 x、y 和 z 坐标。所有坐标都在一个矩阵中;按 x、y、z 排序。每三列包含一个矩形的四个角坐标。我想在一个图中显示所有矩形。但是,它不显示任何矩形。这是我的代码:
%Coordinates(1,3*i-2:3*i) = top left corners' x y z coordinates
%Coordinates(2,3*i-2:3*i) = down left corners' x y z coordinates
%Coordinates(3,3*i-2:3*i) = down right corners' x y z coordinates
%Coordinates(4,3*i-2:3*i) = top right corners' x y z coordinates
这段代码工作正常... [~,c] = 大小(坐标); 对于我 = 1:3:c 补丁(坐标(:,i),坐标(:,i + 1),坐标(:,i + 2)) 坚持,稍等 结束
最佳答案
如果我是对的,您正在寻找类似以下解决方案的东西。这个想法取自Amro的回答here .
想法
代码首先创建带有起始顶点和终止顶点的向量。然后,它创建一个包含起始顶点、终止顶点的线的矩阵,并插入一条 nan 线。然后它使用 patch
绘制曲面并使面不可见。请注意,对于确实很多顶点,这会“浪费”一些 nans
内存,但 patch 命令非常快,因为它只创建一个对象。
代码
% Sample coordinates
coord = [ 1 -1.3 -1;...
-1 -1.3 -1;...
-1 -1.3 1;...
1 -1.3 1;...
1 1.3 -1;...
-1 1.3 -1;...
-1 1.3 1;...
1 1.3 1;...
-1.3 1 -1;...
-1.3 -1 -1;...
-1.3 -1 1;...
-1.3 1 1;...
1.3 1 -1;...
1.3 -1 -1;...
1.3 -1 1;...
1.3 1 1;...
1 -1 -1.3;...
-1 -1 -1.3;...
-1 1 -1.3;...
1 1 -1.3;...
1 -1 1.3;...
-1 -1 1.3;...
-1 1 1.3;...
1 1 1.3];
nlines = size(coord, 1);
% Vectors for vertices
X = zeros(2, nlines);
Y = zeros(2, nlines);
Z = zeros(2, nlines);
C = zeros(1, nlines);
% One iteration per vertex
for ii = 1:nlines
% Here comes the edge back to the first vertex
if mod(ii,4) == 0
X(1, ii) = coord(ii, 1);
Y(1, ii) = coord(ii, 2);
Z(1, ii) = coord(ii, 3);
X(2, ii) = coord(ii-3, 1);
Y(2, ii) = coord(ii-3, 2);
Z(2, ii) = coord(ii-3, 3);
% Here come all other edges
else
X(1, ii) = coord(ii, 1);
Y(1, ii) = coord(ii, 2);
Z(1, ii) = coord(ii, 3);
X(2, ii) = coord(ii+1, 1);
Y(2, ii) = coord(ii+1, 2);
Z(2, ii) = coord(ii+1, 3);
end
% One color for each rectangle
C(ii) = floor((ii-1)/4);
end
% Insert nans between lines
X(end+1, :) = nan;
Xf = X(:);
Y(end+1, :) = nan;
Yf = Y(:);
Z(end+1, :) = nan;
Zf = Z(:);
% Setup patch matrix
p = [Xf, Yf, Zf];
% Prepare color matrix
r = repmat(C.', 1, 3)';
clr = r(:);
% Make a figure
f = figure;
% Plot patch
surface(p(:,[1 1]), p(:,[2 2]), p(:,[3 3]), [clr clr], ...
'EdgeColor', 'flat', ....
'FaceColor', 'None')
grid on
view([55, 36]);
xlabel('X')
ylabel('Y')
zlabel('Z')
情节
关于matlab - 在 Matlab 中使用 patch 绘制多个 3D 矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28046205/