user3639557
user3639557

Reputation: 5311

A random normally distributed matrix in numpy

I would like to generate a matrix M, whose elements M(i,j) are from a standard normal distribution. One trivial way of doing it is,

import numpy as np

A = [ [np.random.normal() for i in range(3)]    for j in range(3) ]
A = np.array(A)
print(A)

[[-0.12409887  0.86569787 -1.62461893]
 [ 0.30234536  0.47554092 -1.41780764]
 [ 0.44443707 -0.76518672 -1.40276347]]

But, I was playing around with numpy and came across another "solution":

import numpy as np
import numpy.matlib as npm

A = np.random.normal(npm.zeros((3, 3)), npm.ones((3, 3)))
print(A)

[[ 1.36542538 -0.40676747  0.51832243]
 [ 1.94915748 -0.86427391 -0.47288974]
 [ 1.9303462  -1.26666448 -0.50629403]]

I read the document for numpy.random.normal, and it says it doesn't clarify how does this function work when matrix is passed instead of a single value. I suspected that in the second "solution" I might be drawing from a multivariate normal distribution. But this can't be true because the input arguments both have the same dimensions (covariance should be a matrix and mean is a vector). Not sure what is being generated by the second code.

Upvotes: 5

Views: 15019

Answers (1)

StefanS
StefanS

Reputation: 1770

The intended way to do what you want is

A = np.random.normal(0, 1, (3, 3))

This is the optional size parameter that tells numpy what shape you want returned (3 by 3 in this case).

Your second way works too, because the documentation states

If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

So there is no multivariate distribution and no correlation.

Upvotes: 11

Related Questions