如何使用MATLAB生成不同形状的3D矩阵? [关闭]

问题描述 投票:1回答:1

我正在尝试生成不同形状的3D矩阵,如下图所示,如圆柱体,圆柱孔或圆环形等.enter image description here

我尝试使用以下代码在3D中生成带有一些内部立方体的立方体,如下所示。

% numbers are arbitrary
cube=zeros(11,11,11);
cube(3:9,3:9,3:9)=5; % Create a cube inside the region
% Boring: faces of the cube are a different color.
cube(3:9,3:9,3)=2;
cube(3:9,3:9,9)=2;
cube(3:9,3,3:9)=2;
cube(3:9,9,3:9)=2;
cube(3,3:9,3:9)=2;
cube(9,3:9,3:9)=2;
vold3d('Cdata',cube,'alpha',cube/5)

我得到的结果如下enter image description here

即使我可以在笛卡尔坐标系中生成这些形状。但我无法生成矩阵。

如何为上述形状生成3D矩阵。该矩阵可以是128x128x128或512x512x512大小。有人可以帮忙吗?提前致谢

matlab 3d shape
1个回答
0
投票

我不完全确定你想要什么输出,但你可以采用以下方法,其中一个形状由一个函数定义,该函数返回逻辑值,告诉一个点是否在形状内。这样,您可以拥有所需的网格分辨率。

function q47822954
RESOLUTION = 5E-2;
[XX,YY,ZZ] = meshgrid(-5:RESOLUTION:5);
%% Cylinder
% Define cylinder:
x0 = 1; y0 = 0;
r_min = 0.8; r_max = 1;
h_min = -1;  h_max = 1;

cyl = inCylinder(x0,y0,r_min,r_max,h_min,h_max,[XX(:),YY(:),ZZ(:)]);
figure(); scatter3(XX(cyl),YY(cyl),ZZ(cyl));
%% Torus
% Define torus:
R = 3;
r = 1;
z0 = -1;
tor = inTorus(x0,y0,z0,R,r,[XX(:),YY(:),ZZ(:)]);
figure(); scatter3(XX(tor),YY(tor),ZZ(tor));
%% Ellipsoid
% Define ellipsoid:
a = 1; b = 2; c = 3;
ell = inEllipsoid(x0,y0,z0,a,b,c,[XX(:),YY(:),ZZ(:)]);
figure(); scatter3(XX(ell),YY(ell),ZZ(ell));
end

function tf = inCylinder(x0,y0,r_min,r_max,h_min,h_max,xyz)
  % xyz is a N-by-3 vector of cartesian coordinates to test
  [~,rho,z] = cart2pol(xyz(:,1)-x0,xyz(:,2)-y0,xyz(:,3));
  tf = rho >= r_min & rho <= r_max & z >= h_min & z <= h_max;
end

function tf = inTorus(x0,y0,z0,R,r,xyz)
  % Torus around the z axis
  assert(R>r); % make sure that this is a torus and not something else
  tf = (R - sqrt( (xyz(:,1)-x0).^2 + (xyz(:,2)-y0).^2)).^2 + (xyz(:,3)-z0).^2 < r^2;
end

function tf = inEllipsoid(x0,y0,z0,a,b,c,xyz)  
  tf = (xyz(:,1)-x0).^2/a^2 + (xyz(:,2)-y0).^2/b^2 + + (xyz(:,3)-z0).^2/c^2 <= 1;
end

结果:

Cylinder

Torus

Ellipsoid

您也可以使用3d triangulation做类似的事情。

© www.soinside.com 2019 - 2024. All rights reserved.