3
votes

I have generated random 3D points in MATLAB. The length of the array of the points changes at each run. I want to turn these points into spheres. However, I am not successful yet. Scatter plot of my points are like this:

My plot

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

To give you an idea, an example picture to show what I expect to generate:

enter image description here

2
@Wolfie: how is that potential "sabotage"?Cerbrus
@Wolfie I don't think you were being told off. Adriaan asked you to clarify the rationale for your edit.tripleee
@Wolfie: I noticed your edit message "use the SO upload with the exclamation point, not imgur". As I understand it, the upload system does actually use imgur.com. I suspect Stack Exchange and Imgur have a commercial arrangement.halfer
Ah, I see what you mean - yes, that was not clear from the edit message. No worries, it's good to clarify.halfer

2 Answers

9
votes

you can use builtin sphere, multiply by radius and add center coordinates. to plot them all at once you can 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 the spheres similar to your desired out put you can add some graphical properties to surf and add a light object:

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

2
votes

Suppose you had 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 doing this operation on each point. Keep in mind you can increase the number of faces on the sphere, take a look here to see how.