1

Given a scipy.sparse.crs_matrix, I would like to extract the submatrix that in Numpy's dense algebra would be expressed as

 A[0::2, 0::2]

i.e., A_{new}(i,j) = A(2*i,2*j) ("chessboard black-squares matrix").

phimuemue
  • 34,669
  • 9
  • 84
  • 115
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • possible duplicate of [slicing sparse (scipy) matrix](http://stackoverflow.com/questions/7609108/slicing-sparse-scipy-matrix) – Nico Schlömer Jul 29 '13 at 17:59

1 Answers1

1

If you first convert the matrix to COO format it is a piece of cake:

def sps_black_squares(a):
    a = a.tocoo()
    idx = (a.row % 2 == 0) & (a.col % 2 == 0)
    new_shape = tuple((j-1) // 2 + 1 for j in a.shape)
    return sps.csr_matrix((a.data[idx], (a.row[idx]//2, a.col[idx]//2)),
                          shape=new_shape)

%timeit sps_black_squares(a)
1000 loops, best of 3: 315 us per loop

%timeit sps.csr_matrix(a.toarray()[::2, ::2])
100 loops, best of 3: 6.55 ms per loop

np.allclose(sps_black_squares(a).toarray(), a.toarray()[::2, ::2])
Out[119]: True
Jaime
  • 65,696
  • 17
  • 124
  • 159