MATLAB: Find the maximum series of ones in a vector of zeros and ones

arrayfind patternMATLABpatternvector

Hi,
I need to understand when my dataset is changing (I am working with TV filters), and to do it I have done a code ,which is working, to give me a logical 1
if there is a variation from step k to k+1 by means of Kullbach Lieber divergence or a 0. The problem is that I have a kind of ripple in my data so the output vector is
like: [0 0 0 1 0 1 1 0 1 1 1 0 0 0 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 0 0 0].
Now I would like to write a code to find the longest stripe of ones and the indexes (which is when I have the real variation), is there any path that I could follow which I am missing?
So, in the picture in red there is my data set and in cyan and blue a cspline and ischange approximation, since they are not working as expected I would like to cluster the set into steady state and varying to later apply a robust average algorithm (the whole code must be lean, so I must reduce everything to the lowest possible number of values).
I hope to have been clear enough.
Thanks you for your time 🙂

Best Answer

"I would like to write a code to find the longest stripe of ones and the indexes"
This is easily done:
transitions = find(diff([0, yourrowvector, 0]));
%the diff will be 1 when the vector changes from 0 to 1, -1 when it changes from 1 to 0, and 0 otherwise, so find the location of 1 and -1
%padding with 0s to make sure that we detect starting or ending with a 1. This way, we know the first transition is always 0->1, and last 1->0
%therefore odd indexed transitions are starts of runs of 1, even indices are ends of runs
runstarts = transitions(1:2:end); %location of the 1st 1 in a run
runends = transitions(2:2:end) - 1; %locations of the last 1 in a run (the transition occurs at the 0 after that)
runlengths = runends - runstarts + 1;
[longestrun, runindex] = max(runlengths);
longestrunstart = runstarts(runindex);
edit: swapped ends and starts!