Summing submatrices of numpy boolean arrays

I have a boolean matrix 11x51

a

. On this I do this operation in Matlab to get a boolean matrix of size 10x50

.

a = logical(a(1:end-1,1:end-1) + a(2:end,1:end-1) + a(1:end-1,2:end) + a(2:end,2:end))

      

I want to do this in python. I tried this: -

a = np.zeros([11,51], dtype=bool)
a=a[0:-2,0:-2] + a[1:-1,0:-2] + a[0:-2,1:-1] + a[1:-1,1:-1]

      

I ended up with a matrix 9x49

and I'm not sure if it does the expected operation.

Can anyone point out the error?

+3


source to share


2 answers


Using slicing

, this would be -

a_out = (a[:-1,:-1] + a[1:,:-1] + a[:-1,1:] + a[1:,1:]).astype(bool)

      

Since it is a

already a boolean array, we can skip the conversion bool

.

An example of a run on MATLAB -



>> a = logical([
    1, 1, 0, 1, 1, 0
    0, 1, 0, 0, 0, 0
    1, 1, 0, 1, 1, 1
    0, 0, 0, 0, 1, 0
    0, 0, 1, 0, 1, 1
    0, 0, 0, 1, 1, 0]);
>> a(1:end-1,1:end-1) + a(2:end,1:end-1) + a(1:end-1,2:end) + a(2:end,2:end)
ans =
     3     2     1     2     1
     3     2     1     2     2
     2     1     1     3     3
     0     1     1     2     3
     0     1     2     3     3
>> logical(a(1:end-1,1:end-1) + a(2:end,1:end-1) + ...
           a(1:end-1,2:end)   + a(2:end,2:end))
ans =
     1     1     1     1     1
     1     1     1     1     1
     1     1     1     1     1
     0     1     1     1     1
     0     1     1     1     1

      

An example of a NumPy run -

In [160]: a  # Same data as in MATLAB sample
Out[160]: 
array([[ True,  True, False,  True,  True, False],
       [False,  True, False, False, False, False],
       [ True,  True, False,  True,  True,  True],
       [False, False, False, False,  True, False],
       [False, False,  True, False,  True,  True],
       [False, False, False,  True,  True, False]], dtype=bool)

In [161]: (a[:-1,:-1] + a[1:,:-1] + a[:-1,1:] + a[1:,1:])
Out[161]: 
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [False,  True,  True,  True,  True],
       [False,  True,  True,  True,  True]], dtype=bool)

      

+2


source


Slicing in python is a little different from Matlab. Try them in Python:

Everything except the last item:

[:-1]

      



Everything except the first item:

[1:]    

      

+1


source







All Articles