1

I have a multidimensional array but I won't know the number of dimensions or the size of each dimension. How can I generalize the code such that I can access each element of the array individually?

import numpy as np
import random

myRand = np.random.rand(5, 6, 7)

#print (myRand.shape[0])
# This works great if I already know that myRand has 3 dimensions. What if I don't know that?
mySum = 0.0
for i in range(myRand.shape[0]):
    for j in range(myRand.shape[1]):
        for k in range(myRand.shape[2]):
#           Do something with myRand[i,j,k]
0

2 Answers 2

1

You could use itertools to do so.

the following piece of code will generate the indices which you will be able to access the array while obtaining them:

import numpy as np
import itertools

v1 = np.random.randint(5, size=2)
v2 = np.random.randint(5, size=(2, 4))
v3 = np.random.randint(5, size=(2, 3, 2))

# v1
args1 = [list(range(e)) for e in list(v1.shape)]
print(v1)
for combination in itertools.product(*args1):
    print(v1[combination])

# v2
args2 = [list(range(e)) for e in list(v2.shape)]
print(v2)
for combination in itertools.product(*args2):
    print(v2[combination])

# v3
args3 = [list(range(e)) for e in list(v3.shape)]
print(v3)
for combination in itertools.product(*args3):
    print(v3[combination])

Tested it on a simple arrays with different sizes and it works fine.

Sign up to request clarification or add additional context in comments.

Comments

1

If you do not need to retain the indices within each of the dimensions for calculation, you can just use numpy.nditer

>>> a = np.arange(8).reshape((2, 2, 2))
>>> a
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

>>> for i in np.nditer(a):
...     print(i)
...
0
1
2
3
4
5
6
7

You shouldn't really need to iterate over the array using a for-loop like this. There is usually a better way to perform whatever computation you are doing using numpy methods

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.