I need to populate a 2D array whose shape is 3xN, where N is initially unknown. The code looks as follows:
import numpy as np
import random
nruns = 5
all_data = [[]]
for run in range(nruns):
n = random.randint(1,10)
d1 = random.sample(range(0, 30), n)
d2 = random.sample(range(0, 30), n)
d3 = random.sample(range(0, 30), n)
data_tmp = [d1, d2, d3]
all_data = np.concatenate((all_data,data_tmp),axis=0)
This gives the following error:
ValueError Traceback (most recent call last)
<ipython-input-103-22af8f04e7c0> in <module>
10 d3 = random.sample(range(0, 30), n)
11 data_tmp = [d1, d2, d3]
---> 12 all_data = np.concatenate((all_data,data_tmp),axis=0)
13 print(np.shape(data_tmp))
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 4
Is there a way to do this without pre-allocating all_data? Note that in my application, the data will not be random, but generated inside the loop.
Many thanks!