MATLAB: Help counting a string of 1s in 2018a

countstring

I want to write a function that will detect and count the number of strings of consecutive 1's in a vector.
For example, if I have a vector of [01110011100], I am looking for a function that will give me an answer of 2, as there are 2 strings of consequetive 1s

Best Answer

  • You can use something like this:
    A=[0 1 1 1 0 0 1 1 1 0 0]
    A1 = [1,diff(A)]~=0;
    Count = [A(A1)'];
    Required_Answer=sum(Count(:) == 1)