Why do I get "Array indices must be positive integers or logical values" when I am trying to plot my functions?

1 次查看(过去 30 天)
figure(1)
alpha=0.89;
beta=0.89;
gamma=0.5;
c(0)=1;
i(0)=1;
y(0)=2;
for t=1:50
y(t) = c(t) + i(t);
c(t) = alpha*y(t - 1);
i(t) = beta*(c(t) - c(t - 1)) + gamma;
end
plot(y,'LineWidth',2)
hold on
plot(c,'LineWidth',2)
plot(i,'LineWidth',2)
xlabel('Time period')
ylabel('BKT (M€)')
Hey! I am trying to plot this, but for some reason I get the message "Array indices must be positive integers or logical values". What seems to be the problem in my code?

采纳的回答

Mathieu NOE
Mathieu NOE 2024-1-31
hello
1/ matlab is a language where indexing is 1 based and not zero based
2/ next correction is that y must be computed once c and i are updated in the for loop
so a working code is :
figure(1)
alpha=0.89;
beta=0.89;
gamma=0.5;
c(1)=1;
i(1)=1;
y(1)=2;
for t=2:50
c(t) = alpha*y(t - 1);
i(t) = beta*(c(t) - c(t - 1)) + gamma;
y(t) = c(t) + i(t);
end
plot(y,'LineWidth',2)
hold on
plot(c,'LineWidth',2)
plot(i,'LineWidth',2)
xlabel('Time period')
ylabel('BKT (M€)')

更多回答(2 个)

Austin M. Weber
Austin M. Weber 2024-1-31
编辑:Austin M. Weber 2024-1-31
In MATLAB, indexing starts at 1, so you cannot have C(0), i(0), or y(0). Rather, it needs to be C(1), i(1), or y(1).
EDIT: @Mathieu NOE is correct, in addition to what I said, that also means that you need to start your for-loop at index position 2 instead of position 1. Otherwise, when your script gets to this line:
for t = 1:50
c(t) = alpha*y(t - 1);
You will still get an error because y(t-1) would be the same as y(0) in the first iteration of the loop. So, you have to start the loop at t = 2:50:
for t = 2:50

Image Analyst
Image Analyst 2024-1-31

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by