Slicing will return you the elements from the matrix based on the start /end index given.

The syntax for slicing is:

[start:end]

  • If the start index is not given, it is considered as 0. For example [:5], it means as [0:5].
  • If the end is not passed, it will take as the length of the array.
  • If the start/end has negative values, it will the slicing will be done from the end of the array.

Before we work on slicing on a matrix, let us first understand how to apply slice on a simple array.

import numpy as np

arr = np.array([2,4,6,8,10,12,14,16])
print(arr[3:6]) # will print the elements from 3 to 5
print(arr[:5]) # will print the elements from 0 to 4
print(arr[2:]) # will print the elements from 2 to length of the array.
print(arr[-5:-1]) # will print from the end i.e. -5 to -2
print(arr[:-1]) # will print from end i.e. 0 to -2