3

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?

1
  • [:-2] will remove two elements
    – Stephen Rauch
    May 7, 2017 at 20:19

2 Answers 2

2

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)
1

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

All but last element:

[:-1]

All but first element:

[1:]    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.