1

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?

4
  • I don't believe this is enough information to answer your question. How about a minimal reproducible example? Commented Mar 6, 2018 at 16:01
  • Sorry, I have to update it. It may missing some sentence Commented Mar 6, 2018 at 16:01
  • Just a note, it's extremely inefficient to continually append to numpy arrays. This involves repeated memory reallocation. Instead, declare the size of the array when you instantiate it, then fill it. Commented Mar 6, 2018 at 16:01
  • @cᴏʟᴅsᴘᴇᴇᴅ: I have updated it, Please look at it Commented Mar 6, 2018 at 16:05

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.