title: Find number of consecutive ones in binary array
body: <p>I want to find the lengths of all series of ones and zeros in a logical array in MATLAB. This is what I did:</p>
  
  <pre><code>A = logical([0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 0 1 1 1 1 1]);
  %// Find series of ones:
  csA = cumsum(A);
  csOnes = csA(diff([A 0]) == -1);
  seriesOnes = [csOnes(1) diff(csOnes)];
  %// Find series of zeros (same way, using ~A)
  csNegA = sumsum(~A);
  csZeros = csNegA(diff([~A 0]) == -1);
  seriesZeros = [csZeros(1) diff(csZeros)];
  </code></pre>
  
  <p>This works, and gives <code>seriesOnes = [4 2 5]</code> and <code>seriesZeros = [3 1 6]</code>. However it is rather ugly in my opinion.</p>
  
  <p>I want to know if there is a better way to do this. Performance is not an issue as this is inexpensive (<code>A</code> is no longer than a few thousand elements). I am looking for code clarity and elegance.</p>
  
  <p>If nothing better can be done, I'll just put this in a little helper function so I don't have to look at it.</p>