Errors in loops in Matlab

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.

回答 (2 件)

Steven Lord
Steven Lord 2022 年 10 月 28 日

0 投票

k(1)=0.6*k_steady;
I assume you haven't preallocated k, so k has just 1 element.
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
Star Strider 2022 年 10 月 28 日

0 投票

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.
.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

質問済み:

2022 年 10 月 28 日

回答済み:

2022 年 10 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by