...

/

Array and Matrix Indexing

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.

Press + to interact
Starting index in MATLAB and Python
Starting index in MATLAB and Python

In MATLAB, round brackets () are used for indexing.

Press + to interact
arr = [1,2,3,4,5]
% print first element
first_element = arr(1)
% print last element
last_element = arr(end)
arr = [1, 2,3 ;...
4, 5, 6]
% print element of first row and second column
element = arr(1, 2)
% print second column
column = arr(:, 2)

In Python, square brackets [] are used to retrieve an element in a list or array at the specified index.

Press + to interact
import numpy as np
# 1D Array
arr = np.array([1, 2, 3, 4, 5])
# print array
print("arr \n",arr)
# print first element
first_element = arr[0]
print("first element = ",first_element)
# print last element
last_element = arr[-1]
print("last element = ",last_element)
# 2D Array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# print array
print("arr \n",arr)
# print element of first row and second column
element = arr[0, 1]
print("element = ",element)
# print second column
column = arr[:, 1]
print( "column =\n",column)

Negative indexing

In both MATLAB and Python, negative indexing allows us to access elements of an array or ...