Create random numpy matrix of same size as another.

17,027

np.random.randn takes the shape of the array as its input which you can get directly from the shape property of the first array. You have to unpack a.shape with the * operator in order to get the proper input for np.random.randn.

a = np.zeros([2, 3])
print(a.shape)
# outputs: (2, 3)
b = np.random.randn(*a.shape)
print(b.shape)
# outputs: (2, 3)
Share:
17,027
TheGrapeBeyond
Author by

TheGrapeBeyond

Gardening, signal processing, and the performing arts!

Updated on June 21, 2022

Comments

  • TheGrapeBeyond
    TheGrapeBeyond almost 2 years

    This question here was useful, but mine is slightly different.

    I am trying to do something simple here, I have a numpy matrix A, and I simply want to create another numpy matrix B, of the same shape as A, but I want B to be created from numpy.random.randn() How can this be done? Thanks.

  • TheGrapeBeyond
    TheGrapeBeyond almost 8 years
    Thanks! But what's with the '*'?
  • Chris Mueller
    Chris Mueller almost 8 years
    @TheGrapeBeyond It unpacks the arguments. Have a look at this question.
  • TheGrapeBeyond
    TheGrapeBeyond almost 8 years
    Very interesting. Thanks, TIL.