How to form a sphere with 1's in a 3D matrix

19 ビュー (過去 30 日間)
Vinit Nagda
Vinit Nagda 2021 年 8 月 31 日
コメント済み: Vinit Nagda 2021 年 8 月 31 日
I have a matrix X=zeros(m,n,p);
If I know the radius value and matrix index for centroid position of sphere, how do I distribute 1's in the matrix such that it forms a sphere in the matrix? (Ignore part of sphere if it goes outside matrix dimensions)
Thank you.

採用された回答

Wan Ji
Wan Ji 2021 年 8 月 31 日
編集済み: Wan Ji 2021 年 8 月 31 日
If there is no scale factor effect with different directions:
m = 80; n = 100; p=90;
[px,py,pz] = meshgrid(1:n, 1:m, 1:p);
radius = 20;
xc = 40; yc = 30; zc = 60; % the center of sphere
logicalSphere = (px-xc).^2 + (py-yc).^2 + (pz-zc).^2 <=radius*radius;
X = zeros(m,n,p);
X(logicalSphere) = 1; % set to zero
You can also show this sphere with isosurface and patch function
axis([0,n,0,m,0,p])
p=patch(isosurface(px,py,pz,X,0));
set(p, 'FaceColor', 'red', 'EdgeColor', 'none');
daspect([1 1 1])
view(3)
hold on
scatter3(px(:),py(:),pz(:),1,X(:),'filled')
camlight; lighting phong
The sphere is shown like

その他の回答 (2 件)

Matt J
Matt J 2021 年 8 月 31 日
編集済み: Matt J 2021 年 8 月 31 日
Using ndgridVecs from the file exchange
[dX,dY,dZ]=ndgridVecs((1:m)-cm, (1:n)-cn, (1:p)-cp); %centroid=[cm,cn,cp]
sphere3D=(dX.^2 + dY.^2 + dZ.^2<=radius^2); %the result
  1 件のコメント
Vinit Nagda
Vinit Nagda 2021 年 8 月 31 日
@Matt J Thanks a lot for your response. Using ndgridVecs fucntion is actually very efficient.

サインインしてコメントする。


Chunru
Chunru 2021 年 8 月 31 日
編集済み: Chunru 2021 年 8 月 31 日
[m, n, p] = deal(10, 12, 14);
[xg, yg, zg] = ndgrid(1:m, 1:n, 1:p);
xc = round(m/2); yc=round(n/2); zc=round(p/2); % center
r = 3;
idx = (xg-xc).^2 + (yg-yc).^2 + (zg-zc).^2 <= r.^2;
s = false(size(xg)); % the sphere
s(idx) = true;
plot3(xg(s), yg(s), zg(s), 'o');
grid on; box on

カテゴリ

Help Center および File ExchangeLighting, Transparency, and Shading についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by