Home > Back-end >  How to plot a 2d Function in MATLAB
How to plot a 2d Function in MATLAB

Time:10-01

I am trying to plot a simple equation in MATLAB.

The equation is

z = x^2 - y^2, for -3 <= x <= 3, -3 <= y <= 3.

The current code that I have is

x = -3:3;
y = -3:3;
z = (x.^2) - (y.^2);
plot(z)

The result is

Please help me in this case because I am not sure if the code and graph is correct. Thank you very much.

CodePudding user response:

There is a lot going wrong here: Let's start at the beginning:

x = -3:3;
y = -3:3;

If we evaluate these they both will return an vector of integers:

x =

-3  -2  -1   0   1   2   3

This means that the grid on which the function is evaluated is going to be very coarse. To alleviate this you can define a step size, e.g. x = 3:0.1:3 or use linspace, in which case you set the number of samples, so e.g. x = linspace(-3, 3, 500). Now consider the next line:

z = (x.^2) - (y.^2);

If we evaluate this we get

z =
0   0   0   0   0   0   0

and you plot this vector with the 2d-plotting function

plot(z)

which perfectly explains why you get a straight line. This is because the automatic broadcasting of the arithmetic operators like minuse (-) just subtracts values entry-wise. You however want to evaluate z for each possible pair of values of x and y. To do this and to get a nice plot later you should use meshgrid, and use a plotting function like mesh to plot it. So I'd recommend using

[X,Y] = meshgrid(x,y);

to create the grid and then evaluate the function on the grid as follows

Z = X.^2 - Y.^2;

and finally plot your function with

mesh(X,Y,Z);

CodePudding user response:

This is not a piecewise function. A Piecewise Function is a function defined by multiple sub-functions, where each sub-function applies to a different interval in the domain. There is only one function here that takes two arrays of the same length. The calculations yield a vector of zeros, due to the input arrays. If you change either one of the vectors, that is "x" or "y", you will see a nonzero plot. Your code works as expected.

  • Related