3
votes

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.

2

2 Answers

1
votes

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

If you're using numpy (you should), you can do this

import numpy as np
m=np.reshape(range(36),(6,6))
ix=(0,3,4,5)
m[ix,:][:,ix]

array([[ 0,  3,  4,  5],
       [18, 21, 22, 23],
       [24, 27, 28, 29],
       [30, 33, 34, 35]])