Array and Matrix Indexing
Perform indexing on arrays and matrices in MATLAB and Python.
Indexing
Indexing is a way to access elements of an array. It allows us to select and manipulate specific elements or groups of elements in an array. We can access a single element of an array by specifying its row and column indexes.
In MATLAB, arrays and matrices are indexed starting at 1, while in Python, they are indexed starting at 0. This means that the first element of an array or matrix in MATLAB is at index 1, while in Python, it is at index 0.
In MATLAB, round brackets ()
are used for indexing.
arr = [1,2,3,4,5]% print first elementfirst_element = arr(1)% print last elementlast_element = arr(end)arr = [1, 2,3 ;...4, 5, 6]% print element of first row and second columnelement = arr(1, 2)% print second columncolumn = arr(:, 2)
In Python, square brackets []
are used to retrieve an element in a list or array at the specified index.
import numpy as np# 1D Arrayarr = np.array([1, 2, 3, 4, 5])# print arrayprint("arr \n",arr)# print first elementfirst_element = arr[0]print("first element = ",first_element)# print last elementlast_element = arr[-1]print("last element = ",last_element)# 2D Arrayarr = np.array([[1, 2, 3], [4, 5, 6]])# print arrayprint("arr \n",arr)# print element of first row and second columnelement = arr[0, 1]print("element = ",element)# print second columncolumn = arr[:, 1]print( "column =\n",column)
Negative indexing
In both MATLAB and Python, negative indexing allows us to access elements of an array or ...