1

Is there any simple and efficient way of extracting a non-contiguous submatrix in NumPy? for example, I have a matrix of size 4X4

A=[ [1, 2, 3, 4]
    [5, 6, 7, 8]
    [9, 10, 11, 12]
    [13, 14, 15, 16]]

and I have two lists: r=[1,2](rows) and c=[0,3] (columns) so I want the submatrix:

B=[[5, 8]
   [9, 12]]

Thanks

MRm
  • 517
  • 2
  • 14

1 Answers1

2

Use np.ix_:

import numpy as np
A=np.array([ [1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]])
r=[1,2]
c=[0,3]
A[np.ix_(r,c)]

Output:

array([[ 5,  8],
       [ 9, 12]])
Code Pope
  • 5,075
  • 8
  • 26
  • 68