0

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

enter image description here

enter image description here

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
1

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I like your meshgrid usage.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.