(MatLab) Count number of occurrences in array and check if bigger than parameter

159 views Asked by At

I am a new user of MatLab and I am stuck with a simple task. I have an array made of 0s and 1s: I need to check if 1s occur more than X time consecutively. i.e. A = [ 0 1 1 1 0 1 0 1 1 1 1 0 1] and I need to know if I have 4 (for example) consecutive 1s in the array ( it only needs to happen once for me to go on with what I am trying to do). If the condition is verified I will then create a new variable, e.g. Y, and set equal to 1 and continue with my script.

Thank you for the help

1

There are 1 answers

3
Vmaxx On

This should do the job: The while loop cuts a vector with 4 elements from the array and compares it to a vector with 4 elements and only ones. If a vector of 4 consecutive ones is contained in A, the variable four_consecutive_ones_found will be set to 1, otherwise it will return 0.

A=[0 1 1 1 0 0 0 1 1 1 0 1 1 1 1];

b=[1 1 1 1];

bool = 0
i_start=1
i_end=4

while bool==0
    C=A(i_start:i_end)

    if C==b
       four_consecutive_ones_found = 1;
       bool = 1
    else
       i_start=i_start+1
       i_end=i_end+1 

       if i_end > numel(A) && bool == 0
           bool =2
           four_consecutive_ones_found = 0;
       end
    end
end 

four_consecutive_ones_found