Matrix Data Structure

Mandeep Singh Saluja
5 min readJun 15, 2024

--

Matrix Data Structure is a two-dimensional array arranged in rows and columns. The intersection of a row and column is called a cell. All the data is stored across different cells in the matrix. Matrix data structure is used when we want to store data in the form of table or grid. Each element in a matrix is identified by its row and column indices.

It is also considered as an array of arrays, where array at each index has the same size.

Components of Matrix Data Structure

  • Size: A matrix has a specific size, defined by its number of rows and columns.
  • Transpose: By flipping a matrix along its main diagonal and switching the rows and columns, you can create the transpose of the matrix.
  • Rank: In many applications, including the solution of linear equations and linear regression analysis, the rank of a matrix — a measure of its linearly independent rows or columns — is utilized.

Declaration of Matrix Data Structure:

Declaration of a Matrix or two-dimensional array is very much similar to that of a one-dimensional array, given as follows.

# Defining number of rows and columns in matrix
number_of_rows = 3
number_of_columns = 3
# Declaring a matrix of size 3 X 3, and initializing it with value zero
rows, cols = (3, 3)
arr = [[0]*cols]*rows
print(arr)

Output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Initializing Matrix Data Structure:

In initialization, we assign some initial value to all the cells of the matrix.

# Initializing a 2-D array with values
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

Operations on Matrix Data Structure:

We can perform a variety of operations on the Matrix Data Structure. Some of the most common operations are:

1. Access elements of Matrix Data Structure:

Like one-dimensional arrays, matrices can be accessed randomly by using their indices to access the individual elements. A cell has two indices, one for its row number, and the other for its column number. We can use arr[i][j] to access the element which is at the ith row and jth column of the matrix.

# Initializing a 2-D array with values
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing elements of 2-D array
print("First element of first row:", arr[0][0])
print("Third element of second row:", arr[1][2])
print("Second element of third row:", arr[2][1])

2. Traversal of a Matrix Data Structure:

We can traverse all the elements of a matrix or two-dimensional array by using two for-loops.

arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
# Traversing over all the rows
for i in range(0, 3):
# Traversing over all the columns of each row
for j in range(0, 4):
print(arr[i][j], end=" ")
print("")

Output

1 2 3 4 
5 6 7 8
9 10 11 12

Row-wise vs column-wise traversal of matrix

Two common ways of traversing a matrix are row-major-order and column-major-order.
Row Major Order: When matrix is accessed row by row.
Column Major Order: When matrix is accessed column by column.
Examples:

Input: mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output: Row-wise: 1 2 3 4 5 6 7 8 9
Column-wise : 1 4 7 2 5 8 3 6 9

Difference: If we see according to time complexity, both lead to O(n2), but accessing elements in a row-major order is generally faster due to better cache utilization.

# Python3 program showing time difference in row major and column major
# access taking MAX 10000 so that time difference can be shown

from time import perf_counter

MAX = 1000

arr = [[0 for i in range(MAX)] for i in range(MAX)]

def rowMajor():
global arr

# accessing element row wise

for i in range(MAX):
for j in range(MAX):
arr[i][j] += 1

def colMajor():
global arr

# accessing element column wise
for i in range(MAX):
for j in range(MAX):
arr[j][i] += 1

# Driver code
if __name__ == '__main__':

# Time taken by row major order
t = perf_counter()
rowMajor()
t = perf_counter() - t
print("Row major access time :{:.2f} s".format(t))

# Time taken by column major order
t = perf_counter()
colMajor()
t = perf_counter() - t
print("Column major access time :{:.2f} s".format(t))

Output:

Row major access time :0.492000 s
Column major access time :1.621000 s

Time Complexity: O(MAX*MAX)
Auxiliary Space: O(MAX*MAX)

3. Searching in a Matrix Data Structure:

We can search an element in a matrix by traversing all the elements of the matrix. Below is the implementation to search an element in a matrix:

# Python code for above approach
def searchInMatrix(arr, x):
# m=4,n=5
for i in range(0, 4):
for j in range(0, 5):
if(arr[i][j] == x):
return 1
return
x = 8
arr = [[0, 6, 8, 9, 11],
[20, 22, 28, 29, 31],
[36, 38, 50, 61, 63],
[64, 66, 100, 122, 128]]
if(searchInMatrix(arr, x)):
print("YES")
else:
print("NO")

Output

YES

Applications of Matrix Data Structure:

  • In Algorithms: Matrix are frequently used in problems based on Dynamic Programming to store the answer to already computed states.
  • Image processing: Images can be represented as a matrix of pixels, where each pixel corresponds to an element in the matrix. This helps in preforming different operations on images.
  • Robotics: In robotics, matrices are used to represent the position and orientation of robots and their end-effectors. They are used to calculate the kinematics and dynamics of robot arms, and to plan their trajectories.
  • Transportation and logistics: Matrices are used in transportation and logistics to represent transportation networks and to solve optimization problems such as the transportation problem and the assignment problem.
  • Finance: Matrices are used in finance to represent portfolios of assets, to calculate the risk and return of investments, and to perform operations such as asset allocation and optimization.
  • Linear Algebra: Matrices are widely used in linear algebra, a branch of mathematics that deals with linear equations, vector spaces, and linear transformations. Matrices are used to represent linear equations and to solve systems of linear equations.

Advantages of Matrix Data Structure:

  • It helps in 2D Visualization.

Disadvantages of Matrix Data Structure:

  • Space inefficient when we need to store very few elements in the matrix.
  • The matrix size should be needed beforehand.
  • Insertion and deletion operations are costly if shifting occurs.
  • Resizing a matrix is time-consuming.

--

--