1

I have a numpy matrix that looks like:

matrix = [[0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
         [0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
           1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
         [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]  

How would I get the length of the longest sequence of 1s or 0s? Also how would I get their start and stop positions?

Is there an easier numpy-way to get this done?

Output format is flexible as long as it denotes the inner list index, the length value, and value's list indices.

Example:
LONGEST ONES: 1, 16, 2, 17 (index of inner list, length, longest 1s sequence index start, longest 1s sequence end pos.). or [1, 16, 2, 17]/(1, 16, 2, 17)
LONGEST ZEROS: 2, 45, 0, 45

Not a duplicate of these questions as this concerns a matrix:
find the start position of the longest sequence of 1's

The result(longest) should be considered among all lists.
A sequence count does not continue when it reaches the end of an inner list.

rafaelc
  • 57,686
  • 15
  • 58
  • 82
Jay Jung
  • 1,805
  • 3
  • 23
  • 46

1 Answers1

1

Using Divakar's base answer, you can adapt by using np.vectorize, setting the argument signature and doing simple math operations to get what you're looking for.

Take, for instance,

m = np.array(matrix)

def get_longest_ones_matrix(b):
    idx_pairs = np.where(np.diff(np.hstack(([False], b==1, [False]))))[0].reshape(-1,2)
    if not idx_pairs.size: return(np.array([0,0,0]))

    d = np.diff(idx_pairs, axis=1).argmax()

    start_longest_seq = idx_pairs[d,0]
    end_longest_seq   = idx_pairs[d,1]

    l = end_longest_seq - start_longest_seq
    p = start_longest_seq % 45
    e = end_longest_seq - 1
    return(np.array([l,p,e])) 

s = m.shape[-1]

v = np.vectorize(get_longest_ones_matrix, signature=f'(s)->(1)')
x = v(m)

Which yields

[[ 3 26 28]
 [16  2 17]
 [ 0  0  0]]

Then,

a = x[:,0].argmax()
print(a,x[a])
1 [16  2 17]
rafaelc
  • 57,686
  • 15
  • 58
  • 82