Matlab中球面函数的等高线图中的输入误差

时间:2013-05-26 15:54:59

标签: matlab debugging

我正在尝试使用等高线图绘制球体函数,但我不断收到以下错误。

??? Error using ==> Z must be size 2x2 or greater.

错误在于这行代码:

contour(X1, X2, Z);

这是球体功能:

function ph = sphere(x)
         ph = sum(x.*x, 2);
end

以下是使用等高线图绘制球体的代码:

min = -25;
max = 25;
h = 25;
c= linspace(min, max, h); % Create the mesh
[X1, X2] = meshgrid(c, c); % Create the grid

Z = sphere(X1,X2);

figure;
icontour(X1, X2, Z);

我希望Z至少返回2x2矩阵。 Z应该是球体的高度,X1是x轴,X2是y轴。

如何消除错误?

1 个答案:

答案 0 :(得分:1)

sum功能中的问题是sphere。虽然X1X225x25矩阵,但ph25x1向量。试试这个:

function ph = sphere(x)

ph = x.*x;  

在这种情况下,您的值ph将与您的网格变量具有相同的维度。

修改

如果您使用更新的方法:

Z = arrayfun(@sphere, X1);

您将获得常量线,因为您只需将X1传递给spheres函数。在这种情况下,它与:

相同
ph = sum(x.^2,2);  

要获取球体,您希望传递两个参数,X1X2

function ph = sphere(x1,x2)
     ph = sum(x1.*x2, 2);
end  

并致电:

Z = arrayfun(@sphere, X1, X2);

如果你这样调用你修改过的函数,你会得到这个结果:

enter image description here

修改2

注意:如果您在脚本中的其他位置使用sphere,则必须更新对其的每次调用以包含两个输入参数。

编辑3

根据您实施此代码的细致程度,我建议不要使用sphere作为函数的名称,因为Matlab's own function with that name