konstant
konstant

Reputation: 705

How to carry out the following sparse matrix subtraction?

I am trying to do the following array subtraction in Python:

import numpy as np
from scipy.sparse import csr_matrix
a = np.array([[1, 2], [3, 4]])  
b = a[:, None] - a[None, :]
sum_ = np.sum(b, axis=-1)
print(sum_)

The above seems to work. However, if I change the above array a to a sparse matrix:

a = csr_matrix(a)

and do the above steps exactly, I get an error:

IndexError: Index dimension must be <= 2

Any ideas on how to fix this?

Upvotes: 0

Views: 808

Answers (1)

Bernardo Costa
Bernardo Costa

Reputation: 519

numpy style broadcasting has not been implemented for sparse matrices. a[:, None] is not supported for sparse matrices and, in your subtraction, a[:, None] and a[None, :] have different shapes.

Your sparse matrix subtraction can be obtained if you do the broadcasting prior to converting into a sparse matrix, and if both parts of the subtraction have the same shape. For example:

a = np.array([[1, 2], [3, 4]])
b = np.array([[1, 1], [1, 1]])
c = csr_matrix(a) - csr_matrix(b)
sum = np.sum(c)
print(csr_matrix.toarray(c))
print(sum)

Upvotes: 1

Related Questions