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?
0 件のコメント
採用された回答
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
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
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!