How to use "while loop" in this case?

조회 수: 6 (최근 30일)
Armando MAROZZI
Armando MAROZZI 2021년 5월 20일
답변: Scott MacKenzie 2021년 5월 20일
I would like to write a loop that says: "when the number of lags is smaller than the sample size stop it".
This is what I tried:
% N.B. MidasQuantile() is from MIDAS Toolbox
% Random data
y_m = rand(300,1);
% Estimation and forecast
lags = [1:250];
estParams_m = nan(size(lags,2),9);
% Training Sample
while lags(end) < 180
for j =1:length(tau)
if j==1
[estParams_m(lags(end),1:3)] = MidasQuantile(y_m(1:180,:), Quantile',tau(j),'Period',22, 'NumLags', lags(end));
elseif j==2
[estParams_m(lags(end),4:6)] = MidasQuantile(y_m(1:180,:),'Quantile',tau(j),'Period',22, 'NumLags', lags(end));
elseif j==3
[estParams_m(lags(end),7:9)] = MidasQuantile(y_m(1:180,:),'Quantile',tau(j),'Period',22, 'NumLags', lags(end));
end
end
end
Yet, I get no results with this. Basically, I want the loop to run until the number of lags does not exceed the restricted sample size.
Can anyone help me with this?
Thanks!
  댓글 수: 2
Stephen23
Stephen23 2021년 5월 20일
lags = [1:250]; % the square brackets are superfluous. Get rid of them.
..
while lags(end) < 180
lags(end) is 250, which is clearly greater than 180. So your WHILE loop does not even get to run one iteration.
Inside the WHILE loop you do not change lags, so even if it did iterate, your code does not change the condition.
Armando MAROZZI
Armando MAROZZI 2021년 5월 20일
thanks for this. So, would this sort the issue?
while lags(1:end) < 180
....
end

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

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 5월 20일
k=1;
while k < 180
for ..
...
end
k=k+1;
end

추가 답변 (1개)

Scott MacKenzie
Scott MacKenzie 2021년 5월 20일
You've got a for-loop inside a while-loop. This is likely unnescessary. Here's approximately what you need...
sampleSize = 180; % or whatever the sample size is, as per your question
for i=1:length(tau)
% do something that iterates through tau
if i == sampleSize
break; % exit the loop when you have reached the sample size
end
end
You can also set this up like this...
sampleSize = 180; % or whatever the sample size is, as per your question
i = 1;
while true
% do something (using i as index into tau, increment i afterward)
if i > samplesize
break; % exit the loop when you have reached the sample size
end
end

카테고리

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