简体   繁体   中英

How do I generate a multidimensional NumPy array with random numbers with the dimension of another array whose dimension is not declared?

This entry and this entry do not help me. They assume that you already know the tuple shape beforehand, and those ways cannot be used inside functions.

In both of the cases, the shape of the tuple is previously known. So the tuple can be indexed into as tup[i] where tup and i is the tuple and the index respectively.

I need an unknown number of integers to come out of a tuple.

I am trying to use the shape of a multi-dimensional NumPy array to generate another multidimensional array of the same shape with random numbers.

Suppose arr is a multidimensional NumPy array, with dimensions previously unknown. I can use arr.shape to get its dimensions back as a tuple. But a tuple cannot be passed as an argument of the np.random.randn() method. It explicitly requires integers.

If I know the tuple shapes beforehand, I can do it by hardcoding indices to access the elements.

How do I get a sequence of integers from a tuple returned as the shape of an array to generate another multidimensional array of the same shape with random numbers? Any other way to do this?

np.random.randn(*some_array.shape)

randn(d0, d1, ..., dn) has a note at the start of its docs:

This is a convenience function for users porting code from Matlab, and wraps standard_normal . That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones .

standard_normal(size=None) docs has an example:

       >>> s = np.random.standard_normal(size=(3, 4, 2))
       >>> s.shape
       (3, 4, 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM