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!