MATLAB: Count variable length

count if statement

I have a problem since the beginning of this month. It looks very simple but I can't program this into Matlab.
I have a matrix of variable length which consists of zeros and ones
x=[1;0;1;0;1;1;1;1;1;1;0;0;0;0;0;1;1;1;1;1;1;1;0;0;0;0;0;1;1;0]
I have to come up with a new matrix which counts consecutive ones.
x=[1;0;1;0;0;0;0;0;0;6;0;0;0;0;0;0;0;0;0;0;0;7;0;0;0;0;0;0;2;0]
The problem is that the lentgh of the consecutive ones can vary.
I've already tried with this code but it does not work. Can someon help me please?
count=zeros;
for i=20
if x(i,1)>0
count(i,1)=count+1;
elseif x(i,1)<1
count(i,1)=0;
end
end

Best Answer

x1 = [0;x;0].';
P1 = strfind(x1, [0,1]);
P2 = strfind(x1, [1,0]);
Now P1 gives the indexes in x1 just before the starts of run, and P2 gives the indexes in x1 of the ends of runs. The difference between the two gives the lengths of the runs. The P1 index before the start of the run in x1 but x1 has had one value added at its beginning, so the P1 happen to index the locations in the final vector where the lengths have to be stored. Initialize the output matrix to 0s, and then write in the lengths (P2-P1) at the offsets P1.