loop starting from a specific time

조회 수: 3 (최근 30일)
Rico
Rico 2014년 11월 17일
댓글: Geoff Hayes 2014년 11월 17일
I first had to calculate two time paths y_permanent and y_temporary, the codes are the following ones:
y_temporary=zeros(101,1);
psi=0.0001*randn(101,1);
y_temporary(1)=100;
for t=1:29
y_temporary(t+1)=y_temporary(t)*(a+0.0001*psi(t,1));
end
for t=30:32
y_temporary(t+1)=y_temporary(t)*(a-0.2);
end
for t=33:100
y_temporary(t+1)=y_temporary(t)*(a+0.0001*psi(t,1));
end
The path for the permanent change was:
y_permanent=zeros(100,1);
y_permanent(1)=100;
for t=1:100;
y_permanent(t+1)=y_permanent(t)*(1.01+0.0001*psi(t,1)); %alpha is now 1.01
end;
Now, my problem is, that I have to figure out a loop wich starts at time t=33 and stops, when the temporary shocks value is twice as high as the value of the permanent shock, counting the number of periods it needs to do so.
I tried several for loops, while loops and combination of a while and if loop but with no success.
If someone could give me a hint how to easily create such a loop, I would be so glad! I'm desperately looking for an answer.
Best Rico

채택된 답변

Geoff Hayes
Geoff Hayes 2014년 11월 17일
Rico - if a period is just one iteration of your for loop (so since your arrays have 101 elements, then there are 101 periods), then you could try the following
numPeriods = 0;
criteriaMet = false;
for k=33:length(y_temporary)
if y_temporary(k)>=2*y_permanent(k)
% the temporary shock value is at least twice that of the
% permanent shock, so we are done
criteriaMet = true;
break;
end
numPeriods = numPeriods + 1;
end
Note how we use break to exit the for loop once the criteria has been met. We use criteriaMet to determine if we ever did find a period where the temporary shock was at least twice that for the permanent.
  댓글 수: 2
Rico
Rico 2014년 11월 17일
Dear Geoff
Thank you very much for your professionel response.
I first had to extend the periods and then I used your code. In the end, it worked perfectly, so thank you very much!!!
Have a nice evening
Best Rico
Geoff Hayes
Geoff Hayes 2014년 11월 17일
Glad it worked out, Rico!

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

추가 답변 (0개)

카테고리

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