How to find the longest interval of 1 in a list [matlab]

I need to find the longest interval 1 in the matrix and the position of the first "1" in that interval.

For example if i have a matrix: [1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 ]

      

I need to have both length 7 and first position 1.1.

Any suggestions on how to proceed would be appreciated.

+3


source to share


3 answers


Using this anwser as a basis, you can do the following:

a = [1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 ]


dsig = diff([0 a 0]);
startIndex = find(dsig > 0);
endIndex = find(dsig < 0) - 1;
duration = endIndex-startIndex+1;
duration

startIdx = startIndex(duration == max(duration))
endIdx = endIndex(duration == max(duration))

      

Output:



duration =

     1     3     7


startIdx =

    11


endIdx =

    17

      

Note that this probably needs to be double checked if it works for other cases than your example. However, I think this is a path in the right direction. If not, you can find more information and possibilities in the linked underserter.

+1


source


If there are multiple bins of the same length, this will only give the position of the first bin.



A=round(rand(1,20)) %// test vector
[~,p2]=find(diff([0 A])==1); %// finds where a string of 1 starts
[~,p3]=find(diff([A 0])==-1); %// finds where a string of 1 ends
le=p3-p2+1; %// length of each interval of 1's
ML=max(le); %// length of longest interval
ML %// display ML
p2(le==ML) %// find where strings of maximum length begin (per Marcin answer)

      

0


source


I was thinking about a brute force approach;

clc; clear all; close all;
A=  [1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 ];
index = 1;
globalCount = 0;
count = 0;
flag = 0; %// A flag to keep if the previous encounter was 0 or 1 
for i = 1 : length(A)
    if A(i) == 1
        count = count + 1;
        if flag == 0 
            index = i
            flag = 1;
        end

    end
    if A(i) == 0 || i == length(A)
        if count > globalCount
            globalCount = count;
        end
        flag = 0;
        count = 0;
    end

end

      

0


source







All Articles