4

I am trying to figure out how to iteratively append 2D arrays to generate a singular larger array. On each iteration a 16x200 ndarray is generated as seen below:

Array to iteratively 'append'

For each iteration a new 16x200 array is generated, I would like to 'append' this to the previously generated array for a total of N iterations. For example for two iterations the first generated array would be 16x200 and for the second iteration the newly generated 16x200 array would be appended to the first creating a 16x400 sized array.

train = np.array([])
for i in [1, 2, 1, 2]:  
    spike_count = [0, 0, 0, 0]
    img = cv2.imread("images/" + str(i) + ".png", 0)  # Read the associated image to be classified
    k = np.array(temporallyEncode(img, 200, 4))
    #  Somehow append k to train on each iteration

In the case of the above embedded code the loop iterates 4 times so the final train array is expected to be 16x800 in size. Any help would be greatly appreciated, I have drawn a blank on how to successfully accomplish this. The code below is a general case:

import numpy as np

totalArray = np.array([])
for i in range(1,3):
    arrayToAppend = totalArray = np.zeros((4, 200))
    # Append arrayToAppend to totalArray somehow

2 Answers 2

8

While it is possible to perform a concatenate (or one of the 'stack' variants) at each iteration, it is generally faster to accumulate the arrays in a list, and perform the concatenate once. List append is simpler and faster.

alist = []
for i in range(0,3):
    arrayToAppend = totalArray = np.zeros((4, 200))
    alist.append(arrayToAppend)
arr = np.concatenate(alist, axis=1)   # to get (4,600)
# hstack does the same thing   
# vstack is the same, but with axis=0   # (12,200)
# stack creates new dimension,   # (3,4,200), (4,3,200) etc
Sign up to request clarification or add additional context in comments.

Comments

0

Try using numpy hstack. From the documention, hstack takes a sequence of arrays and stack them horizontally to make a single array.

For example:

import numpy as np

x = np.zeros((16, 200))
y = x.copy()

for i in xrange(5):
    y = np.hstack([y, x])
    print y.shape

Gives:

(16, 400)
(16, 600)
(16, 800)
(16, 1000)
(16, 1200)

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.