MATLAB: Starting location of vector

starting location of vector

i am using the code to find maximum zero span
g = [ 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 ]
pos1 = find(g==1);
zero_span = diff(pos1)-1;
max_zero_span = max(zero_span)
as from vector g we can see that maximum zero span is starting from location 3. how can i find this with the help of MATLAB.

Best Answer

This is a variation on run length encoding, for which you'll find plenty of functions on the FileExchange.
In any case, it's trivial to do, if you diff your vector, you'll have -1 for transitions from 1 to 0, +1 for transitions from 0 to 1 and 0 elsewhere. The difference between find on the 1 and -1 will give you the lengths of the runs. To make sure that you find the start of a zero run that starts from the beginning of the vector, prepend it with a 1. Same for the end:
g = [ 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 ];
transitions = diff([1 g 1]);
runstarts = find(transitions == -1);
runends = find(transitions == 1);
%because of the 1 padding you're guaranteed there's always the same number of starts and ends
runlengths = runends - runstarts;
[maxlength, runindex] = max(runlengths);
fprintf('\nThe longest run has length %d, starting at index %d\n\n', maxlength, runstarts(runindex))