Add multiple of a matrix without build a new one
<p>Say I have two matrices <code>B</code> and <code>M</code> and I want to execute the following statement:</p>

<pre><code>B += 3*M
</code></pre>

<p>I execute this instruction repeatedly so I don't want to build each time the matrix <code>3*M</code> (<code>3</code> 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"?</p>

<p>More precisely, I have a list of scalars <code>as</code> and a list of matrices <code>Ms</code>, 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:</p>

<pre><code>sum(a*M for a, M in zip(as, Ms))
</code></pre>

<p>The <code>np.dot</code> function does not do what I except...</p>

<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html"><code>np.tensordot</code></a> -</p>

<pre><code>np.tensordot(As,Ms,axes=(0,0))
</code></pre>

<p>Or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html"><code>np.einsum</code></a> -</p>

<pre><code>np.einsum('i,ijk-&gt;jk',As,Ms)
</code></pre>

<p>Sample run -</p>

<pre><code>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-&gt;jk',As,Ms)
Out[45]: 
array([[  6.79630284,   5.04212877,  10.76217631],
       [  4.91927651,   1.98115548,   6.13705742]])
</code></pre>

python numpy matrix