Errors in loops in Matlab
Show older comments
Hello! I am trying to run this code but get the error "Index exceeds the number of array elements. Index must not exceed 1.". Could anybody help to correct it? I want to get for each c1 en epsilon (the difference between the capital stock in the last period t=100 and steady state).
k(1)=0.6*k_steady;
for i=1:length(c1)
c(1)=c1(i);
for t=2:100
k(t+1)=alpha*k(t)^(alpha-1)+(1-delta)*k(t)-c(t);
c(t+1)=(c(t)^sigma/(sigma-1))*(beta(1+alpha*k(t+1)-delta))^1/(sigma-1);
e(i)=abs(k(100)-k_steady);
end
end
Thank you in advance.
Answers (2)
Steven Lord
on 28 Oct 2022
k(1)=0.6*k_steady;
for i=1:length(c1)
c(1)=c1(i);
I also assume you haven't preallocated c, so c has just 1 element.
for t=2:100
k(t+1)=alpha*k(t)^(alpha-1)+(1-delta)*k(t)-c(t);
When t is equal to 2, you're trying to assign to element 3 of k (which doesn't exist yet, but that's fine; assigning to an element that doesn't exist can work) but you're trying to use element 2 of k and element 2 of c to compute that value. Since neither k nor c have 2 elements, this can't work.
I think you want your loop to run from t = 1 to t = 100. In that case when t = 1 you create the second element of k using the first element of k and the first element of c (both of which exist) then on the next line you'd perform a similar assignment to the second element of c. Then at the next iteration when t is 2 you'll assign to the third elements of k and c using the second element of k and c (which you created during the t = 1 iteration.)
Star Strider
on 28 Oct 2022
0 votes
Perhaps you intended:
k(t+1)=alpha*k(t)^(alpha-1)+(1-delta)*k(t)-c1(t);
↑
instead?
That could work if ‘c1’ has 100 elements.
.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!