How to exit a for loop whenever we can't find XX consecutive non-zero values??Momentum Portfolio Construction

Hi everyone. I am trying to construct momentum portfolios but I encounter some missing values problem.
I converted all missing values into 0 and I calculate the number of eligible values (non-missing) in every row in the first loop.
Then I calculate the six month returns of every stock just by adding the simple returns over 6 months.
The problem comes when there's a missing values (which is '0') let's say at month '3'. With my loop number 2 I add these zero as zero return months, when they were missing values.
What I would like to do is to exit the loop whenever there's a 0 in the first or in the following 5 months. Whenever there are not 6 non-zero consecutive values, matlab should return me with empty cases.
Let's say if there's a 0 on the 4th month, it should return empty case till month n4 and then restart looping from month number 5.
Any help? Thank you veeeery much
for i=1:totalmonths
sum0=sum(stockdata(i,:)==0);
sumstockdata(i,:)=sum0;
nbrstocks(i) = totalstocks - sumstockdata(i);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for j=1:1026
for i=1:487
k=i+5;
somma(i,j) = sum(stockdata((i:k),j));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j=1:1026
for i=1:487
k=i+5;
if stockdata(i,j)==0
somma2(i,j)=0;
else
somma2(i,j) = sum(stockdata((i:k),j));
end
end
end

Answers (0)

This question is closed.

Asked:

on 16 Feb 2014

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!