Indexing multidimensional arrays

5.12.1. Indexing multidimensional arrays#

As for unidimensional arrays, we index multidimensional arrays using integers in brackets. Using a single integer indexes the first dimension. For example:

Example 1: Read the marker position at first sample

_images/7adf4c782df32722b252fb8084bb02028b375e4636ee72ce25c4a0e128adea49.png
import numpy as np

position = np.array(
    [
        [0.497, 0.973, 0.010, 1.0],
        [0.528, 0.973, 0.017, 1.0],
        [0.589, 0.970, 0.025, 1.0],
    ]
)

position[0]
array([0.497, 0.973, 0.01 , 1.   ])

Example 2: Read the marker position at second sample

_images/8b5ffe9594d8b5db6e36966361f381895f9f910b6ec1afb9b2c4ce1550554266.png
position[1]
array([0.528, 0.973, 0.017, 1.   ])

Look how indexing an array reduces its dimension by one. In the example above, we indexed the second row of a 2d array, which returned a 1d array that corresponds to the four columns of this row. Therefore, to also select a column, we can index the result:

Example 3: Read the marker’s z coordinate at second sample

_images/2e7bce000558384d985c6053abdd675e50becbab774cea8e38f15e24c40e296a.png
position[1][2]
0.017

This is perfectly valid. However, we normally use commas , to directly access the specified value:

position[1, 2]
0.017

Both notations are equivalent, but the second one is more powerful (as we will see later in section Slicing multidimensional arrays). It makes it also clearer that we index one whole array, and not a list that is nested into another list.

Example 4: Read the segment’s orientation at second sample

_images/bdb07a18932a426eea032eb7f3262be67215fcc2422aac2e38860cd8fb791fb8.png
# Orientation of the segment at second sample
orientation = np.array(
    [
        [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ],
        [
            [1.0, 0.000, 0.000, 0.0],
            [0.0, 0.999, -0.017, 0.0],
            [0.0, 0.017, 0.999, 0.0],
            [0.0, 0.000, 0.000, 1.0],
        ],
    ]
)

orientation[1]
array([[ 1.   ,  0.   ,  0.   ,  0.   ],
       [ 0.   ,  0.999, -0.017,  0.   ],
       [ 0.   ,  0.017,  0.999,  0.   ],
       [ 0.   ,  0.   ,  0.   ,  1.   ]])

Example 5: Read the 3rd line of the segment’s orientation matrix at second sample

_images/3e59ef6c227dd13cfa671e395bed2a243450a949d42f08ce17394a85b41bde29.png
orientation[1, 2]
array([0.   , 0.017, 0.999, 0.   ])

Example 6: Read 3rd line, 2nd column of the segment’s orientation matrix at 2nd sample

_images/d407962ded37834246c0a14207d426f15ca9a938aa60ce0c264df57b68054d1b.png
orientation[1, 2, 1]
0.017