简体   繁体   English

如何在Matlab中使用Surf绘制球面函数

[英]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. 它是MatLab内置函数。

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. 如果需要查看源代码,请使用:当sphere函数不在路径help sphere时, edit spherehelp sphere

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. 为了完整起见,您的代码无法正常工作,因为您只对[-10,10]中的一些\\ \\对(x,x)上的函数进行求值,因此不会涵盖整个域。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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