1
testMat1 = np.array([[1,2,3,4],[4,5,6,7]])
testMat2 = np.array([[7,8,9,10],[10,11,12,13]])
testMat3 = np.array([[2,4,6,8],[3,5,7,9]])

Here are three matrices of shape (2, 4)

How do I combine them into a multidimensional array with shape (3, 2, 4)?

np.array([testMat1, testMat2, testMat3]) works properly, however this is not what I am looking for because I will be continuously adding more matrices to the array. I need a way to append new matrices to the array. I tried using np.append but it doesn't seem to be meant for this purpose.

4
  • 1
    Usually we recommend appending to a list. Any sort of appending to an array requires making a new array with full copies. It can be done with suitable care about dimensions, but it is less efficient. Commented Aug 25, 2021 at 0:39
  • @hpaulj I see. But I need to work with the numpy ndarray, so I would be appending to the list and converting it to an ndarray repeatedly, which is horribly expensive in both time and memory. Is there a better way to do it? Commented Aug 25, 2021 at 1:02
  • I don't know what's the trade off between between doing np.array(alist) repeated as the list grows, and doing the repeated concatenate. Another way is to initial the array to full size, and "insert" the new arrays as they become available, doing your calcs on the appropriate slice. Commented Aug 25, 2021 at 1:22
  • The underlying issue is that a list contains references to arrays that can be scattered through out memory, while a multidimensional array has the data in one contiguous block. If you want a larger block you have to make a new one. Commented Aug 25, 2021 at 1:26

1 Answer 1

1

You can use np.vstack() to vertically stack the arrays.

In your case the command would look like this: combined = np.vstack(([testMat1], [testMat2], [testMat3])) which will give you the shape (3, 2, 4)

You can continuously add more arrays and update it by using: combined = np.vstack((combined, [testMat4])) which will give you the shape (4, 2, 4)

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.