3
votes

I am trying to draw a sphere in Matlab without using the Sphere Function. This is my code:

r = 2;
[ x,y ] = meshgrid(-4:0.1:4);
z = sqrt(r^2-x.^2-y.^2);
mesh(real(z));
hold on 
mesh(real(-z));

The code above does generate a sphere of equation r^2=x^2+y^2+z^2. The only problem is that there is a horizontal plane slicing the sphere.

My question is how can I plot a sphere that doesn't show the horizontal plane?

The reason I am not using a Sphere function is because I want to plot a surface equation. If I use the Sphere function then Matlab assumes my surface will be a sphere.

3
just loose the sqrt... and scale appropriatelybla

3 Answers

2
votes

You should consider switching to polar coordinates. MATLAB can plot surfaces that are topologically equivalent to a rectangular mesh:

N = 20;
thetavec = linspace(0,pi,N);
phivec = linspace(0,2*pi,2*N);
[th, ph] = meshgrid(thetavec,phivec);
R = ones(size(th)); % should be your R(theta,phi) surface in general

x = R.*sin(th).*cos(ph);
y = R.*sin(th).*sin(ph);
z = R.*cos(th);

figure;
surf(x,y,z);
axis vis3d

result

The trick is that in polar coordinates you have a rectangular mesh.

As you can see in the above formulae, in this convention theta is the polar angle and phi is the azimuthal angle, as it is common in mathematics and physics. You can use sph2cart to do the transformation from spherical to Cartesian coordinates, but then you need to input azimuth and elevation for the angles, which have a bit different definitions.

0
votes

Well there have certainly been nicer plots... but it works, if you just set the entry in the z-matrix to nan:

temp = real(z);
temp(temp==0) = nan; 

Or you can go with an implicit 3D plot. In matlab file exchange you can find an according function (Matlab File Excahnge) The corresponding script would look like this:

f = 'x^2 +y^2 +z^2 -4';
ezimplot3(f,[-5 5])
0
votes

im new here but i did made some for matlab without using sphere function although with fmesh divide the sphere in 2 parts and use 2 functions to plot on positive and one negative

im showing an example for one function could be

f=@(x,y) sqrt(3 - (sqrt(3).*(x-4)).^2 -  (sqrt(3).*(y-2)).^2)-5
              ^                ^                              ^
radius of the sphere    position on x axis            position on z axis

full code

f=@(x,y) sqrt(3 - (sqrt(3).*(x-4)).^2 -  (sqrt(3).*(y-2)).^2)-5
fmesh(f,[-10 10 -10 10],'ShowContours','on')

hold

f1=@(x,y) -sqrt(3 -  (sqrt(3).*(x-4)).^2 -  (sqrt(3).*(y-2)).^2)-5
fmesh(f1,[-10 10 -10 10],'ShowContours','on')

hold off