简体   繁体   中英

How to use surf to plot sphere function in matlab

I'm trying to plot sphere function below, But I'm getting wrong result

在此处输入图片说明

在此处输入图片说明

Here is the code I'm using

x1 = [-10:1:10];
x2 = [-10:1:10];
y = zeros(1,21);

for i = 1:21
    y(i) = sphere([x1(i) x2(i)]);
end
Y = meshgrid(y);
surf(x1,x2,Y);
colormap hsv;

sphere.m

function [y] = sphere(x)
d = length(x);
sum = 0;
for i = 1:d
    sum = sum + x(i)^2;
end
y = sum;
end

sphere(10)

It is a MatLab built in function.

Please enjoy responsibly.

If you need to see the source code use: edit sphere or help sphere when your sphere function is not on the path.

For the sake of completness your code is not working because you are only evaluating your function on the pairs (x,x) for some x \\in [-10,10] so you don't cover the whole domain. It would work with this:

x1 = [-10:1:10];
x2 = [-10:1:10];
y = zeros(1,21);

for i = 1:21
    for j=1:21
        Y(i,j) = sphere([x1(i) x2(j)]);
    end
end
surf(x1,x2,Y);
colormap hsv;

or way faster (because you should always avoid unnecessary loops for computation time reasons):

x1 = meshgrid([-10:1:10]);
x2 = x1';

Y = x1.^2+x2.^2;

surf(x1,x2,Y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM