How can I generate spheres from points in MATLAB?

I have created random 3D points in MATLAB. The length of the point array changes with each run. I want to turn these points into spheres. However, I have not yet been successful. The scatter plot of my points is as follows:

My plot

Each point is represented with x, y and z. Now I want to use these x, y and z as center point and generate spheres with r-radius? How can i do this?

To give you an idea, a sample image to show what I expect to generate:

enter image description here

+3


source to share


2 answers


you can use inline sphere

, multiply by radius and add center coordinates. to build them you can immediately use cellfun

:

% number of spheres
n = 10;
% random xyz center points
xyz = rand(n,3)*10;
% random radius
r = rand(n,1);
% generate unit sphere (radius=1, center=[0,0,0])
[X,Y,Z] = sphere;
% plot function for all spheres
plotfun = @(c,r) surf(X*r + c(1),Y*r + c(2),Z*r + c(3));
% generate figure with "hold on"
figure;
hold on;
axis equal;
grid on;
% plot all spheres
h = cellfun(plotfun,num2cell(xyz,2),num2cell(r),'UniformOutput',0);

      

enter image description here



If you want spheres similar to your desired ones, you can add some graphical properties to surf

and add an object light

:

plotfun = @(c,r) surf(x*r + c(1),y*r + c(2),z*r + c(3),...
    'FaceColor',.7*[1 1 1],'EdgeColor','none',...
    'FaceLighting','gouraud','AmbientStrength',0.5);
light('Position',[-1 0 0]);

      

enter image description here

+8


source


Suppose you have a point (a1, a2, a3) and you wanted to plot a sphere of radius R, this is how you could do it:

R=5;
a1=1;
a2=-2;
a3=3;
[x,y,z] = sphere;
surf((x+a1)*R,(y+a2)*R,(z+a3)*R) % centered at (a1,a2,a3) with radius R

      



I suggest looping through your array and performing this operation at every point. Keep in mind that you can increase the number of faces on the sphere, take a look here to see how.

+2


source







All Articles