"Index exceeds the number of array elements"

Hello,
Could someone help me to fix this? I don't know why when I try to run the code, it says that "Index exceeds the number of array elements".
Thank you so much in advance!!!
%GIVEN CONDITIONS
A = 1;
d = 0.05;
alpha = 0.3;
eta = 1;
beta = 0.9;
%DECLARE T
T = 100;
%ASSUME INITIAL CONDITION
k_0 = 1.0588;
%PREALLOCATING SPACE FOR EQUILIBRIUM
k = zeros(T + 1,1);
h = zeros(T + 1,1);
c = zeros(T + 1,1);
w = zeros(T + 1,1);
r = zeros(T + 1,1);
xi_1 = zeros(T + 1,1);
xi_2 = zeros(T + 1,1);
time = zeros(T + 1,1);
%FILL FIRST ELEMENT
k(1,1) = k_0;
%CREATE OUR LOOP:
for i = 1:T+1
time(i) = i-1;
c(i) = ((beta/(c(i+1)))*((r(i+1)) + 1 - d))/ 1 ;
c(i) = ((eta/(1-h(i)))*(1/(w(i))))/ 1 ;
r(i) = A * (alpha) * ( ((h(i))/(k(i)))^(1-alpha) );
w(i) = A * (1- alpha) * ( ((k(i))/(h(i)))^(alpha) );
c(i) = A * ( (k(i)) ^ (alpha) ) * ( (h(i)) ^ (1-alpha) ) + ((1-d) * (k(i))) - (k(i+1));
end
Index exceeds the number of array elements. Index must not exceed 101.

回答(1 个)

Jan
Jan 2022-3-9
编辑:Jan 2022-3-9
The loop fails in the last iteration due to k(i+1). This requests k(T+2), which is not existing. So maybe this solves the problem:
for i = 1:T
or create a longer k.
Avoid overdoing of parentheses. Compare the readability of these two lines:
c(i) = ((beta/(c(i+1)))*((r(i+1)) + 1 - d))/ 1 ;
c(i) = beta / c(i+1) * (r(i+1) + 1 - d);
or:
c(i) = A * ( (k(i)) ^ (alpha) ) * ( (h(i)) ^ (1-alpha) ) + ((1-d) * (k(i))) - (k(i+1));
c(i) = A * k(i) ^ alpha * h(i) ^ (1-alpha) + (1 - d) * k(i) - k(i+1);
By the way, your code overwrites c(i) repeatedly.

2 个评论

Thank you so much! I really appreciate it.
By using:
for i = 1:T
my problem of "Index exceeds the number of array elements", was solved, however when I run my code, I get NaN values for all my variables. Do you think that it is because my code overwrites c(i) repeatedly?
I tried to rewrite it like this, but I still get NaN values.
for i = 1:T
time(i) = i-1;
k(i+1) = A * k(i) ^ alpha * h(i) ^ (1-alpha) + (1 - d) * k(i) - c(i);
h(i) = 1 - ((eta * c(i))/ w(i))
w(i) = A * (1- alpha) * (k(i)/h(i))^(alpha);
r(i) = A * alpha * (h(i)/k(i))^(1-alpha);
c(i) = c(i+1)/ (beta * (r(i+1) + 1 - d)) ;
end
Your w(i) is 0 at the time you divide by it in assigning to it in h(i)

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by