user_1_1_1
user_1_1_1

Reputation: 923

summation of sub-matrices of boolean numpy arrays

I have a 11x51 boolean matrix a. On this I do this operation in Matlab to obtain 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 9x49 matrix and I am not sure if it's doing the expected operation.

Can someone point out the mistake?

Upvotes: 3

Views: 79

Answers (2)

Divakar
Divakar

Reputation: 221554

Using slicing, it would be -

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

Since, a is already a boolean array, we can skip the bool conversion.

Sample 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

Sample run on NumPy -

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)

Upvotes: 2

Stephen Rauch
Stephen Rauch

Reputation: 49794

Slicing in python are a bit different than Matlab. Try these in Python:

All but last element:

[:-1]

All but first element:

[1:]    

Upvotes: 1

Related Questions