This task is pretty trivial in NumPy like so
import numpy as np
a= np.array([[1,2,3,0,9],[3,2,6,2,7],[0,0,0,8,0],[1,0,0,0,3]])
a + a[1]
Output:
array([[ 4, 4, 9, 2, 16],
[ 6, 4, 12, 4, 14],
[ 3, 2, 6, 10, 7],
[ 4, 2, 6, 2, 10]])
See how the vector dimensions are automatically broadcasted to each row of the matrix.
But when it comes to sparse matrices, there is a dimension mismatch error.
from scipy.sparse import *
a= csr_matrix([[1,2,3,0,9],[3,2,6,2,7],[0,0,0,8,0],[1,0,0,0,3]])
a + a[1]
Output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-32-74c48fe5106e> in <module>()
2
3 a= csr_matrix([[1,2,3,0,9],[3,2,6,2,7],[0,0,0,8,0],[1,0,0,0,3]])
----> 4 a + a[1]
/opt/anaconda2/lib/python2.7/site-packages/scipy/sparse/compressed.pyc in __add__(self, other)
337 elif isspmatrix(other):
338 if (other.shape != self.shape):
--> 339 raise ValueError("inconsistent shapes")
340
341 return self._binopt(other,'_plus_')
ValueError: inconsistent shapes
There is a function for sparse multiplication, e.g., a.multiply(a[1]) for a * a[1] (which does its job perfectly), but I couldn't find one for addition.
I'm new to sparse matrices. Please help.