Slicing multidimensional arrays

5.12.2. Slicing multidimensional arrays#

We just learned how to index multidimensional matrices using indexes separated by commas. Slicing works the same way: for a given dimension, all we need is to use a slice instead of an index.

Example 1: Read the marker’s y coordinate at samples 0 and 1

_images/0fcf199fcc6aecb28cb43ad3ad1fd5a4eaf3d1bef07c5a2085247fa2c1fbd132.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:2, 1]
array([0.973, 0.973])

Example 2: Read the marker’s y and z coordinates at samples 0 and 1

_images/740d5a0d6ebd3c73e7cf09fdd635a2ab5bd29d3476b94366c672562cfb407068.png
position[0:2, 1:3]
array([[0.973, 0.01 ],
       [0.973, 0.017]])

Tip

A slice can be as simple as a column operator :. This is a slice with no bound, which literally means from the beginning up to the end. In other words, “all data on this axis”.

Example 3: Read the marker’s z coordinate at all samples

_images/3df8f89138d7336e3a770a86fc20a19d929fa2d0311daf72b775640fa9fe3c30.png
position[:, 2]
array([0.01 , 0.017, 0.025])