How to use "while loop" in this case?

6 次查看(过去 30 天)
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
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