0

Say I have the following array a and subset 2x2 matrices from it:

import numpy as np
np.random.seed(0)

a = np.random.randint(9,size=(3,2,2))

for i in range(a.shape[0]):
    m = a[i]
    print(type(m))
    print(m)

<class 'numpy.ndarray'>
[[5 0]
 [3 3]]
<class 'numpy.ndarray'>
[[7 3]
 [5 2]]
<class 'numpy.ndarray'>
[[4 7]
 [6 8]]

Now if I want to loop through each of the matrices I get an error:

for i in range(a.shape[0]):
    m = a[i]
    for j in range(m):
        print(j)

TypeError: only integer scalar arrays can be converted to a scalar index

Why is that ? Can't really debug this typerror.

1
  • range can't take a numpy.ndarray as an argument. What are you trying to do with range(m)? Do you mean for j in m? Commented Feb 14, 2022 at 10:10

1 Answer 1

1

You are trying to take the range of the matrix m, which doesn't exist and thus the error. Instead, you should take the range of its shape[0] as you did in the first line for matrix a.

If you want to loop into each position of each matrix, then

import numpy as np
np.random.seed(0)

a = np.random.randint(9,size=(3,2,2))

for i in range(a.shape[0]):
    m = a[i]
    print(type(m))
    print(m)
    
for i in range(a.shape[0]):
    m = a[i]
    print("---")
    for x in range(m.shape[0]):
        for y in range(m.shape[1]):
            print(m[x,y])
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.