0

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))
2
  • Are you looking for a 3D array or a list/vector of your matrices? Also, why not just have matrix_array.append(np.identity(3)) inside of your for loop? Commented Feb 23, 2017 at 4:10
  • I am looking for a 3d array Commented Feb 23, 2017 at 4:10

1 Answer 1

1

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)
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.