I have a matrix A, and a list of indices, say l = [0,3,4,5]. Is there an easy way to access the 4x4 submatrix of A corresponding to those rows and columns, i.e. A[l,l]? A[l,:] accesses all columns for the rows in l, A[l,1:4] access the rows in l and first four columns of A, but I cannot find a way to access the l column and row indices in this fashion.
The purpose is I want to define a new matrix as, e.g., G = np.eye(4) - A[l,l] or a new vector v = A[l,l]*c for some 4x1 vector c without moving / copying the data stored in A.
IIUC, you can use np.ix_:
>>> A = np.arange(100).reshape(10,10)
>>> L = [0,3,4,5]
>>> np.ix_(L, L)
(array([[0],
[3],
[4],
[5]]), array([[0, 3, 4, 5]]))
>>> A[np.ix_(L, L)]
array([[ 0, 3, 4, 5],
[30, 33, 34, 35],
[40, 43, 44, 45],
[50, 53, 54, 55]])
This can be used to index in for modification purposes as well:
>>> A[np.ix_(L, L)] *= 10
>>> A[np.ix_(L, L)]
array([[ 0, 30, 40, 50],
[300, 330, 340, 350],
[400, 430, 440, 450],
[500, 530, 540, 550]])
Of course, if you'd prefer, you can always construct the arrays returned by ix_ manually:
>>> Larr = np.array(L)
>>> Larr[:,None]
array([[0],
[3],
[4],
[5]])
>>> Larr[None, :]
array([[0, 3, 4, 5]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With