Matlab中Sphere函数的轮廓图输入错误 [英] Input error in Contour plot of a Sphere Function in Matlab

查看:826
本文介绍了Matlab中Sphere函数的轮廓图输入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用等高线绘制一个球体函数,但是我仍然收到以下错误。

 错误使用==> Z必须大小为2x2或更大。 

错误是在这一行代码:



轮廓(X1,X2,Z);

这是球体函数:

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

以下是使用轮廓图绘制球体的代码:

  min = -25; 
max = 25;
h = 25;
c =空格(min,max,h); %创建网格
[X1,X2] = meshgrid(c,c); %创建网格

Z =球(X1,X2);

数字;
icontour(X1,X2,Z);

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



如何消除错误?

解决方案

您的中的问题是 sum 球体功能。而 X1 X2 25x25 矩阵, ph 是一个 25x1 矢量。尝试这样:

 函数ph = sphere(x)

ph = x。* x;

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



修改



如果您使用更新的方法:

  Z = arrayfun(@sphere,X1); 

您将获得不变的行,因为您只需将X1传递到您的球体函数。在这种情况下,与...相同:

  ph = sum(x。^ 2,2); 

要获得一个球体,您要传递两个参数, X1 X2

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

并打电话:

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

如果你打电话给你修改的函数,你会得到这个结果:





编辑2



注意:如果您在某个地方使用球体在你的脚本中,你必须更新每个调用它以包括两个输入参数。



编辑3



根据您实施此代码的细节,我会建议不要使用 sphere 作为函数的名称,因为 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 is supposed to be the height of the sphere and X1 is the x-axis and X2 is the y-axis.

How can I eliminate the error?

解决方案

The problem is sum in your sphere function. While X1 and X2 are 25x25 matrices, phis a 25x1vector. 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.

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. 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:

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

ATTENTION: If you are using sphere somewhere else in your script, you have to update each call to it to include two input arguments.

Edit 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.

这篇关于Matlab中Sphere函数的轮廓图输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆