MATLAB: Create a sphere using surface equation

equationmultipleoutput valuesscaledspheresurface

The surface equation of a sphere is (x-a)^2+(y-b)^2+(z-c)^2-r^2=0.
What I pretend is to create a sphere surface using the equation above. And then get an output matrix with the x,y,z values of the sphere surface nodes…
I don't want to use the sphere function because I intend to create multiple spheres and get the x,y,z values to each one of them. With sphere function I dont know if it would be possible.
Can somebody help me please?

Best Answer

"I don't want to use the sphere function because I intend to create multiple spheres and get the x,y,z values to each one of them."
The solution below contains a function produceSphereCoord() that is based on Matlab's sphere() function but doesn't produce the surface plot. At the top the script below, you can set the number of nodes each sphere will have. Then you can set the number of spheres to create. The 3D coordinates of one sphere is created with [-1,1] normalized units. It's then replicated as many times as requested and the coordinates are stored in a [n-by-3] cell array "xyz" where the columns are values of [x,y,z] coordinates and there's one row for each sphere.
n = 20; %number of nodes per sphere
nSpheres = 6; %number of normalized spheres (-1:1)
xyz = cell(nSpheres, 3); %stores you [x,y,z] coordinates for each sphere
% Create normalized sphere
[x, y, z] = produceSphereCoord(n);
% replicate and store in cell array
xyz(:,1) = repmat({x}, nSpheres,1);
xyz(:,2) = repmat({y}, nSpheres,1);
xyz(:,3) = repmat({z}, nSpheres,1);
function [x, y, z] = produceSphereCoord(n)
% from matlab's sphere() function.
% n is the number of nodes
theta = (-n:2:n)/n*pi;
phi = (-n:2:n)'/n*pi/2;
cosphi = cos(phi); cosphi(1) = 0; cosphi(n+1) = 0;
sintheta = sin(theta); sintheta(1) = 0; sintheta(n+1) = 0;
x = cosphi*cos(theta);
y = cosphi*sintheta;
z = sin(phi)*ones(1,n+1);
end
You can then scale them as needed with the help of cellfun(). In this example, I scale the 6 spheres to 6 different sizes.
scales = {10 8 6 4 2 .5}';
scalesMat = repmat(scales, 1,3);
xyzScaled = cellfun(@(n,s)n.*s, xyz, scalesMat, 'UniformOutput', false);
To plot the results,
cla()
hold on
grid on
box on
colors = jet(size(xyzScaled,1));
arrayfun(@(row)plot3(xyzScaled{row,1},xyzScaled{row,2},xyzScaled{row,3}, 'o', 'color', colors(row,:)), 1:size(xyzScaled,1))
axis equal
view(3)