Matrices addition in numpy
<p>I need to calculate the sum of a list of matrices, however, I can't use <code>np.sum</code>, even with <code>axis=0</code>, I don't know why. The current solution is a loop, but is there a better way for that? </p>

<pre><code>import numpy as np
SAMPLE_SIZES = [10, 100, 1000, 10000]
ITERATIONS = 1
MEAN = np.array([1, 1])
COVARIANCE = np.array([[1, 0.5], [0.5, 1]])
for sample_size in SAMPLE_SIZES:
    max = -1
    for i in range(ITERATIONS):
        xs = np.random.multivariate_normal(MEAN, COVARIANCE, size=sample_size)
        sigma = [[0, 0], [0, 0]]
        for x in xs:
            sigma += np.outer((x-MEAN), (x-MEAN)) / (sample_size-1)
</code></pre>

<p>In the code above, can I replace the last loop using some <code>numpy</code> function? I guess using a loop would be not efficient if the data is very large.</p>

<p>If you just want to compute the empirical covariance then I would suggest using <code>numpy.cov(xs.T)</code>. </p>

<p>Otherwise, the last 3 lines can be replaced by:</p>

<pre><code>xm = xs - np.mean(xs, axis=0)
sigma = np.inner(xm.T. xm.T) / (sample_size-1)
</code></pre>

python numpy