Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the occurrence of consecutive 1s in 0-1 data in MATLAB

Tags:

matlab

I have a set of 1s and 0s. How do I count the maximum number of consecutive 1s?

(For example, x = [ 1 1 0 0 1 1 0 0 0 1 0 0 1 1 1 ....]). Here the answer is 3 because the maximum number of times 1 occurs consecutively is 3.

I was looking at some search and count inbuilt function, however I have not been successful.

like image 391
discipulus Avatar asked Jun 13 '11 12:06

discipulus


People also ask

How do you count values in Matlab?

A = count( str , pat ) returns the number of occurrences of pat in str . If pat is an array containing multiple patterns, then count returns the sum of the occurrences of all elements of pat in str . count matches elements of pat in order, from left to right.

How do you find the number of elements in an array in Matlab?

n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .


2 Answers

Try this:

max( diff( [0 (find( ~ (x > 0) ) ) numel(x) + 1] ) - 1)
like image 129
Eng.Fouad Avatar answered Sep 30 '22 19:09

Eng.Fouad


Here's a solution but it might be overkill:

L = bwlabel(x);
L(L==0) = [];
[~,n] = mode(L)

Sometimes it's better to write your own function with loops ; most of the time it's cleaner and faster.

like image 22
Jacob Avatar answered Sep 30 '22 19:09

Jacob