# How can I create sphere in this code?

2 views (last 30 days)
SHUBHAM SINGH CHOUDHARY on 7 Sep 2020
Answered: Ayush Gupta on 10 Sep 2020
X=(0:0.02:1);
Y=(0:0.02:1);
[x,y] = meshgrid(X,Y);
%z=rand(size(x))*1000;
%z=1e6*ones(size(x));
z=zeros(size(x));
x0=mean(X);
y0=mean(Y);
b_center1 = [0.2,0.8];
b_center2 = [0.6,0.2];
b_center3 = [0.4,0.55];
r1=0.1*max(X);
r2=0.1*max(X);
r3=0.1*max(X);
for i=1:length(X)
for j=1:length(Y)
dist = pdist([[X(i),Y(j)];b_center1]);
if (dist < r1)
z(i,j)=1;
end
dist = pdist([[X(i),Y(j)];b_center2]);
if (dist < r2)
z(i,j)=1;
end
dist = pdist([[X(i),Y(j)];b_center3]);
if (dist < r3)
z(i,j)=1;
end
end
end
surf(x,y,z)

Ayush Gupta on 10 Sep 2020
The above code is not able to generate spheres primarily because in the workflow any point that is less than r1 is given a true value by giving it 1 whereas for a sphere the points should be all equidistant from a center. To plot a sphere with center at (a,b,c) and radius r, refer to the following code:
[x,y,z] = sphere;
x = x*r;
y = y*r;
z = z*r;
figure
surf(x+a,y+b,z+c)