简体   繁体   English

在 Matlab 中绘制 3D 曲面

[英]Plotting a 3D surface in Matlab

I have the following function:我有以下功能:

功能
I want to plot it in MATLAB at −15 ≤ x ≤ 15 and −15 ≤ y ≤ 15.我想在 MATLAB 中将它绘制在 -15 ≤ x ≤ 15 和 -15 ≤ y ≤ 15 处。

What i tried is this:我试过的是这样的:

[x,y] = meshgrid(-15:1:15, -15:1:15);
z = ((x^4 + y^4 - 4 * x^2 * y^2)/(x^2 + y^2));
plot(x,y,z)

When I run it it says Warning: Matrix is singular to working precision.当我运行它时,它说Warning: Matrix is singular to working precision. Data must be a single matrix Y or a list of pairs X,Y.

And my variable z only contains a 31x31 double filled with NaN.而我的变量 z 只包含一个用 NaN 填充的 31x31 双精度值。

The problem is generated by the division by the term x^2+y^2, which in some cases is actually zero, and your incorrect usage of the Matlab operators.问题是由 x^2+y^2 项除法产生的,在某些情况下它实际上为零,以及您对 Matlab 运算符的错误使用。 Lastly, the plot function is not suited for plotting a 3D surface.最后, plot函数不适合绘制 3D 表面。 I'd recommend using a symbolic computation for simplicity:为简单起见,我建议使用符号计算:

syms x y; 
z = ((x^4 + y^4 - 4 * x^2 * y^2)/(x^2 + y^2));
fsurf(z,[-15,15,-15,15])

在此处输入图片说明

You can also use your numeric version (faster), but take care to use the right operators - instead of matrix multiplication * , use element-wise multiplication .* for example.您也可以使用您的数字版本(更快),但要注意使用正确的运算符 - 而不是矩阵乘法* ,例如使用元素乘法.* This is relevant for ^ and / as well.这也与^/相关。

[x,y] = meshgrid(-15:1:15, -15:1:15);
z = ((x.^4 + y.^4 - 4 .* x.^2 .* y.^2)./(x.^2 + y.^2));
surf(x,y,z)

在此处输入图片说明

Note that the origin is not defined in this case - due to the division by zero problem.请注意,在这种情况下未定义原点 - 由于被零除的问题。 You can use a different range to avoid this problem if you'd like.如果您愿意,您可以使用不同的范围来避免此问题。

[x,y] = meshgrid(-15:0.17:15, -15:0.17:15);
z = ((x.^4 + y.^4 - 4 .* x.^2 .* y.^2)./(x.^2 + y.^2));
surf(x,y,z,'EdgeAlpha',0) % The above range is dense - so we remove the edge coloring for clarity. 

在此处输入图片说明

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

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