"Index exceeds the number of array elements"
Show older comments
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
Answers (1)
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 Comments
Maria Ochoa-Tebar
on 9 Mar 2022
Edited: Maria Ochoa-Tebar
on 9 Mar 2022
Walter Roberson
on 9 Mar 2022
Your w(i) is 0 at the time you divide by it in assigning to it in h(i)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!