在Matlab中使用补丁绘制多个3D矩形
我有多个矩形角的x,y和z坐标.所有坐标都在一个矩阵中;按x,y,z排序.每三列包含一个矩形的四个角坐标.我想在一个图中显示所有矩形.但是,它不显示任何矩形.这是我的代码:
I have x, y, and z coordinates of multiple rectangles' corners. All coordinates are in one matrix; ordered as x, y, z. Every three columns contain one rectangle's four corner coordinates. I want to show all rectangles in one plot. However, it does not show any of rectangles. Here is my code:
%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)) 坚持,稍等 结束
This code works fine... [~,c] = size(coordinates); for i = 1:3:c patch(coordinates(:,i),coordinates(:,i+1),coordinates(:,i+2)) hold on end
如果我是对的,那么您正在寻找类似以下解决方案的东西.这个想法来自Amro的答案在这里.
If I'm right, you're looking for somthing like the following solution. The idea is taken from Amro's answer here.
代码首先创建具有起始和终止顶点的向量.然后,它创建一个矩阵,其中包含具有起始顶点,终止顶点的线,并插入nan
线.然后,它使用patch
绘制表面并使该表面不可见.请注意,对于很多顶点,这会浪费" nans
的某些内存,但是patch命令的速度非常快,因为它仅创建一个对象.
The code first creates vectors with start and stop vertices. It then creates a matrix holding lines with the start vertex, stop vertex and inserts a nan
line. Then it uses patch
to plot a surface and makes the face invisible. Note, that for reeeaally many vertices, this "wastes" some memory for the nans
but the patch command is quite fast, as it creates only one object.
% 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')
情节