简体   繁体   中英

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.

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

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. Lastly, the plot function is not suited for plotting a 3D surface. 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. 

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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