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
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
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
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
# 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
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
orientation[1, 2, 1]
0.017