Skip to content Skip to sidebar Skip to footer

How To Create A Sub-matrix In Numpy

I have a two-dimensional NxM numpy array: a = np.ndarray((N,M), dtype=np.float32) I would like to make a sub-matrix with a selected number of columns and matrices. For each dimens

Solution 1:

There are several ways to get submatrix in numpy:

In [35]: ri = [0,2]
    ...: ci = [2,3]
    ...: a[np.reshape(ri, (-1, 1)), ci]
Out[35]: 
array([[ 2,  3],
       [10, 11]])

In [36]: a[np.ix_(ri, ci)]
Out[36]: 
array([[ 2,  3],
       [10, 11]])

In [37]: s=a[np.ix_(ri, ci)]

In [38]: np.may_share_memory(a, s)
Out[38]: False

note that the submatrix you get is a new copy, not a view of the original mat.

Solution 2:

You only need to makes cols and rows be a numpy array, and then you can just use the [] as:

import numpy as np

a = np.array([[ 0,  1,  2,  3],
   [ 4,  5,  6,  7],
   [ 8,  9, 10, 11]])

cols = np.array([True, False, True])
rows = np.array([False, False, True, True])

result = a[cols][:,rows]


print(result) 
print(type(result))
# [[ 2  3]# [10 11]]# <class 'numpy.ndarray'>

Post a Comment for "How To Create A Sub-matrix In Numpy"