Jame
Jame

Reputation: 3854

How to concatenate vectors to create a array in loop?

I have a loop for that generate a new vector (100,) in each iteration. So the code loop likes

for i in range (10):
   for j in range (4):
     #Create a new vector (100,) 
     #Concatenate 4 vector together to make (400,) #400=4*10 
#Append the concatenation vectors (400,) in vertical to make (10,400) array

My expected is that generates a matrix size of (10,400) that concatenate vectors in these loops

Currently, my solution is

   matrix_= np.empty([10,400])
    for i in range (10):
       vector_horz=[]
       for j in range (4):
         #Create a new vector (100,) 
         vector_rnd=#Random make a vector/list with size of (100,1)
         #Concatenate 4 vector together to make (400,) #400=4*10
         vector_horz.append(vector_rnd)
    #Append the concatenation vectors (400,) in vertical to make (10,400) array
       matrix_(:,i)=vector_horz

However, it said that my size of matrix and vector_horz cannot assign. Could you give me another solution?

Upvotes: 1

Views: 746

Answers (1)

cs95
cs95

Reputation: 402523

Option 1
(Recommended) First generate your data and create an array at the end:

data = []
for i in range(10):
    for j in range(4):
        temp_list = ... # random vector of 100 elements 
        data.extend(temp_list) 

arr = np.reshape(data, (10, 400))

Option 2
Alternatively, initialise an empty array with np.empty and assign one slice at a time:

arr = np.empty((10, 400))
for i in range(10):
    for j in range(4):
        temp_list = ...
        arr[i, j * 100 : (j + 1) * 100] = temp_list

Upvotes: 3

Related Questions