Is there a fast way in numpy to add a vector to every row or column of a matrix.
Lately, I have been tiling the vector to the size of the matrix, which can use a lot of memory. For example
mat=np.arange(15)
mat.shape=(5,3)
vec=np.ones(3)
mat+=np.tile(vec, (5,1))
The other way I can think of is using a python loop, but loops are slow:
for i in xrange(len(mat)):
mat[i,:]+=vec
Is there a fast way to do this in numpy without resorting to C extensions?
It would be nice to be able to virtually tile a vector, like a more flexible version of broadcasting. Or to be able to iterate an operation row-wise or column-wise, which you may almost be able to do with some of the ufunc methods.
mat + vec
, so I'm not sure exactly what you're after. [Incidentally, this is anarray
, not amatrix
.] – Aspinwallmatrix
is different from a 2darray
. For example, multiplication is matrix multiplication onmatrix
objects but elementwise onarray
objects, so it's a good idea to keep them distinct. – Aspinwall