1

Im trying to iterate over a Numpy Array that contains 3d numpy arrays (3d vectors) inside it. Something like this:

import numpy as np


Matrix = np.zeros(shape=(10, 3))
# => [
    [0,0,0],
    [0,0,0],
    ...
    [0,0,0]
]

I need to iterate over it, getting each 3d Vector. In pseudo code:

for vector in Matrix
    print vector #=> [0,0,0]

Is there any Numpy native way of doing this? What is the fastest way of doing this?

Thanks!

Fran

1
  • 1
    Terminology note: a 3D numpy array is one whose shape has 3 elements. For example, np.zeros([3, 4, 5]) would be a 3D array. Commented May 20, 2014 at 20:16

1 Answer 1

2

Your pseudocode is only missing a colon:

for vector in matrix:
    print vector

That said, you will generally want to avoid explicit iteration over a NumPy array. Take advantage of broadcasted operations and NumPy built-in functions as much as possible; it moves the loops into C instead of interpreted Python, and it tends to produce shorter code, too.

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

3 Comments

Hi! Thanks for answer. Is there any Numpy way of doing this? Like for example with nditer?
@plant: nditer wouldn't simplify your code or make it run faster; it'd just be unnecessary complication. The NumPy way of doing it would be to not use a loop at all and figure out how to get broadcasting and built-in functions to do the job, but if you really want a loop, this is how you would do it.
That's a very good clear question. So i'll look into broadcasting. Thanks!

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.