Reputation: 356
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?
Upvotes: 0
Views: 1718
Reputation: 231335
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 likenumpy.zeros
andnumpy.ones
.
standard_normal(size=None)
docs has an example:
>>> s = np.random.standard_normal(size=(3, 4, 2))
>>> s.shape
(3, 4, 2)
Upvotes: 1