Sebastien Sebastien - 2 months ago 9
Python Question

Add multiple of a matrix without build a new one

Say I have two matrices

B
and
M
and I want to execute the following statement:

B += 3*M


I execute this instruction repeatedly so I don't want to build each time the matrix
3*M
(
3
may change, it is just to make cleat that I only do a scalar-matrix product). Is it a numpy-function which makes this computation "in place"?

More precisely, I have a list of scalars
as
and a list of matrices
Ms
, I would like to perform the "dot product" (which is not really one since the two operands are of different type) of the two, that is to say:

sum(a*M for a, M in zip(as, Ms))


The
np.dot
function does not do what I except...

Answer

You can use np.tensordot -

np.tensordot(As,Ms,axes=(0,0))

Or np.einsum -

np.einsum('i,ijk->jk',As,Ms)

Sample run -

In [41]: As = [2,5,6]

In [42]: Ms = [np.random.rand(2,3),np.random.rand(2,3),np.random.rand(2,3)]

In [43]: sum(a*M for a, M in zip(As, Ms))
Out[43]: 
array([[  6.79630284,   5.04212877,  10.76217631],
       [  4.91927651,   1.98115548,   6.13705742]])

In [44]: np.tensordot(As,Ms,axes=(0,0))
Out[44]: 
array([[  6.79630284,   5.04212877,  10.76217631],
       [  4.91927651,   1.98115548,   6.13705742]])

In [45]: np.einsum('i,ijk->jk',As,Ms)
Out[45]: 
array([[  6.79630284,   5.04212877,  10.76217631],
       [  4.91927651,   1.98115548,   6.13705742]])