user
user

Reputation: 914

Numpy create an array of matrices

I am trying to store matrices into an array, however when I append the matrix, it would get every element and output just an 1 dimensional array.

Example Code:

matrix_array= np.array([])
for y in y_label:
      matrix_array= np.append(matrix_array, np.identity(3))

Upvotes: 0

Views: 182

Answers (1)

hpaulj
hpaulj

Reputation: 231665

Clearly np.append is the wrong tool for the job:

In [144]: np.append(np.array([]), np.identity(3))
Out[144]: array([ 1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.])

From its docs:

If axis is not specified, values can be any shape and will be flattened before use.

With list append

In [153]: alist=[]
In [154]: for y in [1,2]:
     ...:     alist.append(np.identity(3))
     ...:    
In [155]: alist
Out[155]: 
[array([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]]), array([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]])]
In [156]: np.array(alist)
Out[156]: 
array([[[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]],

       [[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]]])
In [157]: _.shape
Out[157]: (2, 3, 3)

Upvotes: 1

Related Questions