1

MWE: Suppose I have 12 2D-arrays. I want to merge them in some fixed size using loop. The following code gives the result I want to get X. Here I have concatenate 3 2D-arrays, but if I want to fixed this size according my choice using loop, how can I do this?

import numpy as np
a1 = np.array([[0, 12, 3], [5, 8, 9]])
a2 = np.array([[2, 13, 3], [5, 9, 9]])
a3 = np.array([[0, 24, 4], [6, 10, 9]])
a4 = np.array([[1, 55, 6], [4, 5, 19]])
a5 = np.array([[1, 56, 6], [4, 01, 9]])
a6 = np.array([[1, 57, 6], [4, 20, 9]])
a7 = np.array([[1, 58, 6], [4, 30, 9]])
a8 = np.array([[1, 59, 6], [4, 40, 9]])
a9 = np.array([[1, 51, 6], [4, 60, 9]])
a10 = np.array([[1, 34, 6], [4, 60, 9]])
a11 = np.array([[1, 51, 62], [4, 30, 9]])
a12 = np.array([[1, 1, 6], [4, 7, 9]]) 

M=[a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12]
d1 = np.concatenate((a1,a2,a3), 1)
d2 = np.concatenate((a4,a5,a6), 1)
d3 = np.concatenate((a7,a8,a9), 1)
d4 = np.concatenate((a10,a11,a12), 1)
X=[d1,d2,d3,d4]

1 Answer 1

2

Your question is a little bit unclear I assume you want to make the number of concatenated 2D-array (e.g in d1, d2,..) to be variable and do the same thing you did in your code with a loop.

You can do it this way :

This will give the same result as your code, and you can change the variable chosenSize for different results.

    a1 = np.array([[0, 12, 3], [5, 8, 9]])
    a2 = np.array([[2, 13, 3], [5, 9, 9]])
    a3 = np.array([[0, 24, 4], [6, 10, 9]])
    a4 = np.array([[1, 55, 6], [4, 5, 19]])
    a5 = np.array([[1, 56, 6], [4, 1, 9]])
    a6 = np.array([[1, 57, 6], [4, 20, 9]])
    a7 = np.array([[1, 58, 6], [4, 30, 9]])
    a8 = np.array([[1, 59, 6], [4, 40, 9]])
    a9 = np.array([[1, 51, 6], [4, 60, 9]])
    a10 = np.array([[1, 34, 6], [4, 60, 9]])
    a11 = np.array([[1, 51, 62], [4, 30, 9]])
    a12 = np.array([[1, 1, 6], [4, 7, 9]])

    M = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12]
    d1 = []  # will be used to concatenate
    X = []
    chosenSize = 3  # chosen size

    numberOfIterations = M.__len__()//chosenSize

    for i in range(0, numberOfIterations):
        for j in range(0, chosenSize):
            d1.append(M[j + chosenSize * i])
        d1 = np.concatenate(d1, 1)
        X.append(d1)
        d1 = []

    print(X)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.