How do I plot a sphere using the cylinder function?

I know that I can easily plot a sphere using the sphere function, but I am trying to do it with the cylinder function. This is what I have so far, but I can't seem to get the function right.
clc;
x1 = linspace(0,pi,100);
y1 = linspace(0,1,100);
z1 = linspace(0,2,100);
[x2, y2,z2]=cylinder(x.^2+y.^2),200);
figure(2);
surf(x2, y2,z2);
xlabel('X');
ylabel('Y');
zlabel('Z');
colormap(jet)

 采纳的回答

x = linspace(0, 1, 20);
[X, Y, Z] = cylinder(sqrt(x .* (1 - x)));
surf(X, Y, Z);
axis equal
The first input determines the radius. Then h^2 = p*q helps.

2 个评论

Now this is what I have, but I can't seem to get the Z-axis to be from (-1,1) so that the sphere will look not squashed. Please help.
x = linspace(0, 1, 20);
Z=linspace(-1,1,20);
[X, Y, Z] = cylinder(sqrt(2.*x .* (2 - 2.*x)),20);
figure(2);
surf(X, Y,Z);
xlabel('X');
ylabel('Y');
zlabel('Z');
colormap(jet)
Please use the "{} Code" button to format code. This looks nicer than inserting blank lines.
The line "Z=linspace(-1,1,20);" is useless, because Z is overwritten. Does "Z-axis to be from (-1,1)" mean, that you want a radius of 1? With your code, the Z- axis does not only "look squashed", but the object is not a sphere. Multiplying the radius by 2 deforms it, but as explained in the documentation, the height is still set to 1:
cylinder treats each element in r as a radius at equally spaced
heights along the unit height of the cylinder.
Do you want to increase the radius? Then you have to do this with the output of cylinder, not with the input:
x = linspace(0, 1, 20);
[X, Y, Z] = cylinder(sqrt(x .* (1 - x)));
Z = Z - 0.5;
X = X * 2;
Y = Y * 2;
Z = Z * 2;
surf(X, Y, Z);
axis equal
This is a sphere around the origin with radius 1.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 2-D and 3-D Plots 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by