How to extend this code to 3 dimension to get a sphere and how to visualize it?
Show older comments
I have a code with 2 dimension: Nx and Ny. With the following condition i can get the circle of radius 5. Now i want to extend it into 3 dimension Nx, Ny and Nz. The purpose is to get the sphere. How to extend it and which commands should i used to see the output?
Note: I am not looking into any inbuilt function to generate the sphere. Just looking for the extension of this code segment
The code is:
Nx = 64;
Ny = 64;
p = zeros(Nx,Ny);
for i=1:Nx
for j=1:Ny
if ((i-Nx/2)*(i-Nx/2)+(j-Ny/2)*(j-Ny/2) < 10)
p(i,j) = 1.0;
end
end
end
Answers (2)
To extend the code to generate a sphere in 3D, you can introduce an additional dimension Nz and modify the condition inside the nested loops. Here's an extended version of the code:
Nx = 64;
Ny = 64;
Nz = 64;
p = zeros(Nx, Ny, Nz);
for i = 1:Nx
for j = 1:Ny
for k = 1:Nz
if ((i-Nx/2)*(i-Nx/2) + (j-Ny/2)*(j-Ny/2) + (k-Nz/2)*(k-Nz/2) < 10^2)
p(i, j, k) = 1.0;
end
end
end
end
slice(p, [], [], 1:Nz);
axis equal;
4 Comments
Trim Dim
on 15 May 2023
Nx = 64;
Ny = 64;
Nz = 64;
p = zeros(Nx, Ny, Nz);
% Center coordinates of the sphere
center_x = Nx/2;
center_y = Ny/2;
center_z = Nz/2;
radius = 5;
% Generate grid in three dimensions
[X, Y, Z] = meshgrid(1:Nx, 1:Ny, 1:Nz);
% Check if each point is within the sphere
distances = (X - center_x).^2 + (Y - center_y).^2 + (Z - center_z).^2;
p(distances <= radius^2) = 1.0;
% Display the 3D matrix as slices
figure;
slice(p, [], [], 1:Nz);
axis equal;
xlabel('X');
ylabel('Y');
zlabel('Z');
Hi, check this
Trim Dim
on 15 May 2023
Shaik
on 15 May 2023
It's hard to say by seeing the figure actually
Trim Dim
on 15 May 2023
0 votes
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



