Nikko
Nikko

Reputation: 1572

How to set a number not in submatrix of a matrix

Suppose I have a numpy array. I want to set 0 to the indexes NOT in the submatrix mask.

import numpy as np

mtrx = np.arange(25).reshape(5,5)
mask = mtrx[1:4, 1:4]

Of course this is wrong:

mtrx[~mask] = 0

The result I want:

[[ 0  0  0  0  0]
 [ 0  6  7  8  0]
 [ 0 11 12 13  0]
 [ 0 16 17 18  0]
 [ 0  0  0  0  0]]

Upvotes: 1

Views: 130

Answers (3)

yatu
yatu

Reputation: 88276

One way would be to index an array of zeros and add the values from the original array indexed:

s = np.s_[1:4,1:4]
out = np.zeros_like(mtrx)
out[s] = mtrx[s]

print(out)

array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  6.,  7.,  8.,  0.],
       [ 0., 11., 12., 13.,  0.],
       [ 0., 16., 17., 18.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Upvotes: 3

Prudhvi
Prudhvi

Reputation: 1115

One option is to set the rows and columns to zeros.

   import numpy as np

    mtrx = np.arange(25).reshape(5,5)
    mtrx[:1] = 0
    mtrx[-1:] = 0
    mtrx[:,:1] = 0
    mtrx[:, -1:] = 0 
    print(mtrx)
    #output
    #[[ 0  0  0  0  0]
    # [ 0  6  7  8  0]
    # [ 0 11 12 13  0]
    # [ 0 16 17 18  0]
    # [ 0  0  0  0  0]]

Upvotes: 1

R_B
R_B

Reputation: 59

You can multiply the matrix by a mask such as:

import numpy as np
mtrx = np.arange(25).reshape(5,5)
mask = np.zeros((5,5))
mask[1:4,1:4] = 1

mask
>>>array([[0., 0., 0., 0., 0.],
          [0., 1., 1., 1., 0.],
          [0., 1., 1., 1., 0.],
          [0., 1., 1., 1., 0.],
          [0., 0., 0., 0., 0.]])

mtrx * mask
>>> array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  6.,  7.,  8.,  0.],
           [ 0., 11., 12., 13.,  0.],
           [ 0., 16., 17., 18.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]])

Upvotes: 1

Related Questions