[英]Plotting equation in Matlab using for loop
I want to plot an equation using a for-loop. 我想使用for循环绘制方程式。 I have tried several different ways, but keep getting the apparently common error "Subscript indices must either be real positive integers or logicals". 我尝试了几种不同的方法,但是仍然会收到明显的常见错误“下标索引必须是实数正整数或逻辑”。 The equation I want to plot is y(x) = (x^4)-(4*x^3)-(6*x^2)+15 . 我要绘制的方程是y(x)=(x ^ 4)-(4 * x ^ 3)-(6 * x ^ 2)+15 。
The last code I tried was the following: 我尝试的最后一个代码如下:
y(0) = 15;
for x = [-3 -2 -1 0 1 2 3 4 5 6];
y(x) = (x^4)-(4*x^3)-(6*x^2)+15;
end
plot(x,y)
To start from the beginning, 从头开始
y(0) = 15;
will give you the following error: 将给您以下错误:
Subscript indices must either be real positive integers or logicals. 下标索引必须是实数正整数或逻辑值。
This is because Matlab's indexing starts at 1. Other languages like C and Python start at 0. 这是因为Matlab的索引从1开始。其他语言(例如C和Python)从0开始。
Matlab can work directly with vectors. Matlab可以直接使用向量。 So in your code, there is no need for a loop at all. 因此,在您的代码中,根本不需要循环。
You can do it like this: 您可以这样做:
x = [-3 -2 -1 0 1 2 3 4 5 6];
y = (x.^4) - (4*x.^3) - (6*x.^2) + 15;
plot(x, y);
Note that we need to use element-wise operators like .*
and .^
to calculate the values vectorized for every element. 请注意,我们需要使用.*
和.^
这样的逐元素运算符来计算每个元素的矢量化值。 Therefore a point .
因此有一点.
is written in front of the operator. 写在操作员前面。
Additionally, we can improve the code substantially by using the colon operator to generate x
: 另外,我们可以通过使用冒号运算符生成x
来显着改善代码:
x = -3:6; % produces the same as [-3 -2 -1 0 1 2 3 4 5 6]
y = (x.^4) - (4*x.^3) - (6*x.^2) + 15;
plot(x, y);
If you want finer details for your graph, use linspace
as suggested by @Yvon: 如果你想为你的图表更精细的细节,使用linspace
通过@Yvon的建议:
x = linspace(-3, 6, 100); % produces a vector with 100 points between -3 and 6.
y = x.^4-4*x.^3-6*x.^2+15;
plot(x,y)
x = linspace(-3, 6, 100);
y = x.^4-4*x.^3-6*x.^2+15;
plot(x,y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.