[英]Input error in Contour plot of a Sphere Function in Matlab
I am trying to plot a sphere function using contour plot, but I keep getting the following error. 我试图使用等高线图绘制球体函数,但我不断收到以下错误。
??? Error using ==> Z must be size 2x2 or greater.
Error in is at this line of code: 错误在于这行代码:
contour(X1, X2, Z);
Here is the sphere function: 这是球体功能:
function ph = sphere(x)
ph = sum(x.*x, 2);
end
Here is the code to plot the sphere using contour plot: 以下是使用等高线图绘制球体的代码:
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);
I expect Z to return at least a 2x2 matrix. 我希望Z至少返回2x2矩阵。 Z is supposed to be the height of the sphere and X1 is the x-axis and X2 is the y-axis.
Z应该是球体的高度,X1是x轴,X2是y轴。
How can I eliminate the error? 如何消除错误?
The problem is sum
in your sphere
function. 问题是你的
sphere
函数的sum
。 While X1
and X2
are 25x25
matrices, ph
is a 25x1
vector. 虽然
X1
和X2
是25x25
矩阵,但ph
是25x1
向量。 Try this: 尝试这个:
function ph = sphere(x)
ph = x.*x;
In this case, your value ph
will be of the same dimenion as your grid variables. 在这种情况下,您的值
ph
将与您的网格变量具有相同的维度。
Edit 编辑
If you use your updated approach: 如果您使用更新的方法:
Z = arrayfun(@sphere, X1);
You will get constant lines because you just pass X1 to your spheres
function. 你将获得恒定的线条,因为你只需将X1传递给你的
spheres
功能。 Which, in that case is the same as: 其中,在这种情况下是相同的:
ph = sum(x.^2,2);
To get a sphere, you want to pass both arguments, X1
and X2
: 要获得球体,您需要传递两个参数
X1
和X2
:
function ph = sphere(x1,x2)
ph = sum(x1.*x2, 2);
end
And call: 并致电:
Z = arrayfun(@sphere, X1, X2);
If you call your modified function like that, you'll get this result: 如果你这样调用你修改过的函数,你会得到这个结果:
Edit 2 编辑2
ATTENTION: If you are using sphere
somewhere else in your script, you have to update each call to it to include two input arguments. 注意:如果您在脚本中的其他位置使用
sphere
,则必须更新每次调用它以包含两个输入参数。
Edit 3 编辑3
Depending on how carefully you implement this code, I would advise against using sphere
as a name for a function, because of Matlab's own function with that name . 根据您实现此代码的细致程度,我建议不要使用
sphere
作为函数的名称,因为Matlab自己的函数具有该名称 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.