Home > other >  Change/add dimensions to a numpy array
Change/add dimensions to a numpy array

Time:08-03

here is the code I am referring to:

k = np.array([1,2,3,4,5,6])
l = np.array([10,20])
outer = np.outer(l,k)
m = np.random.normal(0, .1, l.shape)

Outer has the shape (2,6) with the results of:

[[ 10  20  30  40  50  60]
 [ 20  40  60  80 100 120]]

I would like m to have the same dimensions. For exmaple, m is equal to:

[-0.14893783 -0.05070178]

I would like it have the same dimensions as outer like so:

[[ -0.14893783  -0.14893783  -0.14893783  -0.14893783  -0.14893783  -0.14893783]
 [ -0.05070178  -0.05070178  -0.05070178  -0.05070178 -0.05070178 -0.05070178]]

At the end I want to be able to add the values of m to every component of the outer matrix and they need to have the same dimensions. How can I do this with numpy?

CodePudding user response:

No need to explicitly reshape. Numpy's broadcasting takes care of that automatically

m.reshape(-1, 1)   outer

Further details on how broadcasting works can be found in the docs

  • Related