Reputation: 35
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.
Upvotes: 1
Views: 539
Reputation: 887
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.
Upvotes: 3