Why do I get "Array indices must be positive integers or logical values" when I am trying to plot my functions?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Jenni
am 31 Jan. 2024
Bearbeitet: Austin M. Weber
am 31 Jan. 2024
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?
0 Kommentare
Akzeptierte Antwort
Mathieu NOE
am 31 Jan. 2024
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€)')
Weitere Antworten (2)
Austin M. Weber
am 31 Jan. 2024
Bearbeitet: Austin M. Weber
am 31 Jan. 2024
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
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!