简体   繁体   English

如何将 plot 变成 MATLAB 中的 2d Function

[英]How to plot a 2d Function in MATLAB

I am trying to plot a simple equation in MATLAB.我正在尝试 plot 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.非常感谢你。

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.这不是分段 function。分段 Function是由多个子函数定义的 function,其中每个子函数适用于域中的不同区间。 There is only one function here that takes two arrays of the same length.这里只有一个function取两个相同长度的arrays。 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.由于输入 arrays,计算会产生一个零向量。如果您更改其中一个向量,即“x”或“y”,您将看到一个非零值 plot。您的代码按预期工作。

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.这意味着评估 function 的网格将非常粗糙。 To alleviate this you can define a step size, eg x = 3:0.1:3 or use linspace , in which case you set the number of samples, so eg x = linspace(-3, 3, 500) .为了缓解这种情况,您可以定义一个步长,例如x = 3:0.1:3或使用linspace ,在这种情况下您可以设置样本数,例如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 这个向量与二维绘图 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 .但是,您想要为xy的每对可能值计算z To do this and to get a nice plot later you should use meshgrid , and use a plotting function like mesh to plot it.要做到这一点并在以后获得漂亮的 plot,您应该使用meshgrid ,并使用像 plot 这样的mesh绘制 function。 So I'd recommend using所以我建议使用

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

to create the grid and then evaluate the function on the grid as follows创建网格,然后在网格上计算 function,如下所示

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

and finally plot your function with最后 plot 你的 function 与

mesh(X,Y,Z);

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

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