-1

I have "n" number of 2D matrices of same size. I want to store all these 2D matrices one by one into a single 3D numpy matrix/array.

Can anyone please tell me how to do this in python?

  • Have you tried to look by yourself before posting here? There's plenty of ways to do it, this question clearly doesn't show enough research effort. – RandomGuy May 10 '21 at 15:15
  • @RandomGuy yes sir, I looked alot but all the methods were storing the 2 to 3 matrices. But I need a method where I would be storing a single matrix one by one into the 3d numpy array. – Saptarshee Sarkar May 10 '21 at 15:19

1 Answers1

0

You can use numpy.dstack() such as:

import numpy as np
a = np.array([[1,2,3],[1,2,3]])
b = np.array([[2,3,4],[2,3,4]])
c = np.array([[3,4,5],[3,4,5]])
new_3d = np.dstack((a,b,c))

Output:

[[[1 2 3]
 [2 3 4]
 [3 4 5]]

[[1 2 3]
 [2 3 4]
 [3 4 5]]]

Update for new question:

Also, you can add another 2d again and again like:

d = np.array([[3,4,5],[3,4,5]])
new_3d = np.dstack((new_3d,d))

Output:

[[[1 2 3 3]
 [2 3 4 4]
 [3 4 5 5]]

 [[1 2 3 3]
 [2 3 4 4]
 [3 4 5 5]]]