Home > Software engineering >  How to create a tensor from a list of matrices in numpy?
How to create a tensor from a list of matrices in numpy?

Time:01-22

A = np.random.rand(3,2)
B = np.random.rand(3,2)
C = np.random.rand(3,2)


How do I create a tensor T that is 3x2x3; as in, T[:,:,0] = A, T[:,:,1] = B, and T[:,:,2] = C? Also I may not know the number of matrices that I may be given before run time, so I cannot explicitly create an empty tensor before hand and fill it.

I tried,

T = np.array([A,B,C])

but that gives me an array where T[0,:,:] = A, T[1,:,:] = B, and T[2,:,:] = C. Not what I wanted.

CodePudding user response:

Is this what you're after? I've used randint instead of rand to make it easier to see in the printed output that the arrays are lined up the way you wanted them.

import numpy as np

A = np.random.randint(0, 20, size=(3, 2))
B = np.random.randint(0, 20, size=(3, 2))
C = np.random.randint(0, 20, size=(3, 2))


T = np.dstack([A, B, C])

print(f'A: \n{A}', end='\n')
print(f'\nT[:,:,0]: \n{T[:,:,0]}\n')

print(f'B: \n{B}', end='\n')
print(f'\nT[:,:,1]: \n{T[:,:,1]}\n')

print(f'C: \n{C}', end='\n')
print(f'\nT[:,:,2]: \n{T[:,:,2]}\n')

Result:

A: 
[[19  9]
 [ 3 19]
 [ 8  6]]

T[:,:,0]:
[[19  9]
 [ 3 19]
 [ 8  6]]

B:
[[16 18]
 [ 8  3]
 [13 18]]

T[:,:,1]:
[[16 18]
 [ 8  3]
 [13 18]]

C:
[[12  9]
 [14 17]
 [16 13]]

T[:,:,2]:
[[12  9]
 [14 17]
 [16 13]]
  • Related