# for loop - Error Attempted to access y(30); index out of bounds because numel(y)=2.

조회 수: 1 (최근 30일)
Rico 2014년 11월 17일
댓글: Rico 2014년 11월 17일
Dear all
I have to compute a time path over t=1:100 periods. I have to assume a temporary shock in t=30:32 so I tried this and used different for loops:
y(1)=100; %(starting value of y) a=1.02;
for t=1:29;
y(t+1)=y(t)*(a+0.0001*randn(1,1));
for t=30:32 (here there is the temporary shock)
y(t+1)=y(t)*(a-0.2);
end;
for t=33:100
y(t+1)=y(t)*(a+0.0001*randn(1,1));
end;
end;
Unfortunately, it gives me the error: Attempted to access y(30); index out of bounds because numel(y)=2.
I really tried different things but couldn't get the loop fixed.

댓글을 달려면 로그인하십시오.

### 채택된 답변

Julia 2014년 11월 17일
Hi,
the best is to define y before you use it.
y=zeros(100,1)
I think your loops are nested in the wrong way. You set t = 1, calculate y(2), enter the next loop and calculate y(31), y(32) and y(33) and then enter the last loop to calculate the entries up to y(100). You do all of this for t = 2 to t = 29. I suggest you execute one loop after the other, this should save a lot of time.
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Rico 2014년 11월 17일
Wow, thank you Julia for your immediate response! It worked perfectly when I used seperate loops, thank you!

댓글을 달려면 로그인하십시오.

### 추가 답변 (1개)

Torsten 2014년 11월 17일
y=zeros(101);
b=randn(101,1);
y(1)=100;
for t=1:29
y(t+1)=y(t)*(a+0.0001*b(t,1));
end
for t=30:32 %(here there is the temporary shock)
y(t+1)=y(t)*(a-0.2);
end
for t=33:100
y(t+1)=y(t)*(a+0.0001*b(t,1));
end
Best wishes
Torsten.
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Rico 2014년 11월 17일
Torsten, thank you very much for your quick reply! I tried yours and it worked perfectly as well.
Have a nice day
best Rico

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by