franleplant
franleplant

Reputation: 639

Numpy iterating over 3d vector array

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

Upvotes: 1

Views: 852

Answers (1)

user2357112
user2357112

Reputation: 280237

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.

Upvotes: 2

Related Questions