Matrix or Grid Data Structure
What is Matrix Data Structure?
Matrix, also referred to as a grid, is a special two-dimensional array in which elements are arranged in rows and columns. We can also say it is an array nested within another array. Each element of the matrix can be identified by the row and column index.
Generally, matrix data structure is used to store and manipulate two-dimensional structures, such as graphs, maps, tables, etc. It can also be used to represent linear equations, transformations, rotations, and other mathematical concepts.

Declaration and Initialization of a Matrix
To declare a matrix, we simply need to specify the data type and name of the matrix followed by two square brackets. These square brackets specify rows and columns of the matrix.
The process of declaration and initialization of the Matrix is very much similar in all the programming languages. Let's look at the syntax for creating a matrix in various programming languages −
data_type array_name[rows][cols] = {elements separated by commas};
In Python programming language, specifying data type is not necessary −
array_name[rows][cols] = {elements separated by commas};
Need for Matrix
Matrices are very useful in various fields including mathematics, computer science, graphics, robotics and many more. Companies worldwide store information of their users in the form of matrix which helps in making recommendations and targeted marketing.
Whether it is our favourite movies or games, all are built with the help of matrix calculation. Many scientific innovations and research directly or indirectly require these calculations.
Matrix Representation
We can represent a Matrix data structure in the form of a table where each element is stored in a single cell. The figure below illustrates how a matrix is represented −

From the above illustration, we can conclude the following important points −
Index starts with 0.
A matrix of 5x3 dimension would have 15 elements.
We can access or locate any element with the help of its row and column indices.
Basic Operations on Matrix
We can manipulate a given matrix data structure by performing various operations on it, such as rotation, addition, multiplication and so on.
Following are the basic operations that can be performed on a given matrix −
- Accessing − Accessing a particular row or column of the matrix.
- Searching − Locating a particular element of the matrix.
- Sorting − Arranging matrix elements in a specific order.
- Insertion − Adds a row at the specified index.
- Deletion − Deletes a row from the matrix.
Matrix - Access Operation
In the access operation, we print the elements of a particular row or column.
Algorithm
Following is an algorithm to access elements of a matrix −
1. Start 2. Declare and initialize a matrix. 3. Access the required row. 4. Print the result. 5. Stop
Example
Here, we see a practical implementation of access operation, where we try to print elements of a row −
#include <stdio.h> int main() { // declaration and initialization of a 3x3 matrix int matrix[3][3] = {{1, 2, 1}, {4, 5, 4}, {7, 8, 7}}; // accessing the second row int* rowScnd = matrix[1]; // loop to print the result printf("Accessing a row: "); for (int i = 0; i < 3; i++) { printf("%d ", rowScnd[i]); } }
#include <iostream> using namespace std; int main() { // declaration and initialization of a 3x3 matrix int matrix[3][3] = {{1, 2, 1}, {4, 5, 4}, {7, 8, 7}}; // accessing the second row int* rowScnd = matrix[1]; // loop to print the result cout<< "Accessing a row: "; for (int i = 0; i < 3; i++) { cout << rowScnd[i] << " "; } cout << endl; }
import java.util.Arrays; public class Main { public static void main(String[] args) { // declaration and initialization of a 3x3 matrix int matrix[][] = {{1, 2, 1}, {4, 5, 4}, {7, 8, 7}}; // accessing the second row int rowScnd[] = matrix[1]; // printing the result System.out.println("Accessing a row: " + Arrays.toString(rowScnd)); } }
# declaration and initialization of a 3x3 matrix matrix = [[1, 2, 1], [4, 5, 4], [7, 8, 7]] # accessing the second row rowScnd = matrix[1] # printing the result print("Accessing a row:" ) print(rowScnd)
Output
Accessing a row: 4 5 4
Matrix - Search Operation
To search for the specified element in a given matrix, we need to loop through each row and column and compare the element with the value we are looking for.
Algorithm
The following algorithm demonstrates how to search an element of a given matrix −
1. Start 2. Declare and initialize a matrix. 3. Define the target element. 4. Use a for loop to search elements in the row. 5. Define another for loop to search elements in the column. 6. If found return the indices, otherwise return [-1, -1]. 7. Stop
Example
Let's see a practical example of search operation in various programming languages −
#include <stdio.h> #include <stdlib.h> // Function to search element int* srchmatrix(int matrix[3][3], int target) { // array to hold the result static int indX[2]; // Looping through each row for (int i = 0; i < 3; i++) { // Looping through each column for (int j = 0; j < 3; j++) { // Comparing the element with the targeted element if (matrix[i][j] == target) { // to return the row and column indices int* indX = malloc(2 * sizeof(int)); indX[0] = i; indX[1] = j; return indX; } } } // return negative value if element not found indX[0] = -1; indX[1] = -1; return indX; } int main() { // declaration and initialization of a 3x3 matrix int matrix[3][3] = {{1, 2, 1}, {4, 5, 4}, {7, 8, 7}}; // calling the function int* indX = srchmatrix(matrix, 5); // to print the result printf("The specified element is at index: [%d, %d] ", indX[0], indX[1]); free(indX); return 0; }
#include <iostream> using namespace std; // Function to search element int* srchmatrix(int matrix[3][3], int targtElem) { // array to hold the result static int indX[2]; // Looping through each row for (int i = 0; i < 3; i++) { // Looping through each column for (int j = 0; j < 3; j++) { // Comparing the element with the targeted element if (matrix[i][j] == targtElem) { // to return the row and column indices indX[0] = i; indX[1] = j; return indX; } } } // return negative value if element not found indX[0] = -1; indX[1] = -1; return indX; } int main() { // declaration and initialization of a 3x3 matrix int matrix[3][3] = {{1, 2, 1}, {4, 5, 4}, {7, 8, 7}}; // calling the function int* indX = srchmatrix(matrix, 5); // to print the result cout << "The specified element is at index: [" << indX[0] << ", " << indX[1] << "]" << endl; return 0; }
public class Main { // method to search element public static int[] srchmatrix(int[][] matrix, int targtElem) { // Looping through each row for (int i = 0; i < matrix.length; i++) { // Looping through each column for (int j = 0; j < matrix[i].length; j++) { // Comparing the element with the desired element if (matrix[i][j] == targtElem) { // to return the row and column indices return new int[]{i, j}; } } } // return negative value if element not found return new int[]{-1, -1}; } public static void main(String[] args) { // declaration and initialization of a 3x3 matrix int[][] matrix = {{1, 2, 1}, {4, 5, 4}, {7, 8, 7}}; // desired element we are looking for int targtElem = 5; // calling the method int[] indX = srchmatrix(matrix, targtElem); // printing the result System.out.println("The specified element is at index: [" + indX[0] + ", " + indX[1] + "]"); } }
# declaration and initialization of a 3x3 matrix matrix = [[1, 2, 1], [4, 5, 4], [7, 8, 7]] # method to search element def searchMatrix(matrix, targtElem): # Looping through each row for i in range(len(matrix)): # Looping through each column for j in range(len(matrix[i])): # Comparing the element with the desired element if matrix[i][j] == targtElem: # to return the row and column indices return (i, j) # Return negative value if element not found return (-1, -1) # desired element we are looking for targtElem = 5 # calling the method indX = searchMatrix(matrix, targtElem) # printing the result print(f"The specified element is at index: {indX}")
Output
The specified element is at index: [1, 1]
Matrix - Sorting Operation
In the sort operation, we arrange the elements of the given matrix in a specified order, such as ascending or descending.
Algorithm
The algorithm to sort elements of a matrix in ascending order is as follows −
1. Start 2. Declare and initialize a matrix. 3. Compare and sort each element of the specified row. 4. Print the result. 5. Stop
Example
In the following example, we see a practical implementation of sorting operation −
#include <stdio.h> // function to sort the array void araySort(int mat[], int n) { for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (mat[j] > mat[j+1]) { // swapping mat[j] and mat[j+1] int temp = mat[j]; mat[j] = mat[j+1]; mat[j+1] = temp; } } } } int main() { // declaration and initialization of 3x4 matrix int matrix[3][4] = {{12, 10, 7, 36}, {20, 9, 8, 4}, {15, 73, 83, 13}}; // Sorting the first row araySort(matrix[0], 4); // Printing the result printf("The matrix after sorting first row: "); for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf(" "); } return 0; }
#include <iostream> #include <algorithm> using namespace std; int main() { // declaration and initialization of 3x4 matrix int matrix[3][4] = {{12, 10, 7, 36}, {20, 9, 8, 4}, {15, 73, 83, 13}}; // Sorting the first row sort(matrix[0], matrix[0] + 4); // Printing the result cout << "The matrix after sorting first row: " << endl; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { cout << matrix[i][j] << " "; } cout << endl; } return 0; }
import java.util.Arrays; public class Main { public static void main(String []args) { // declaration and initialization of 3x4 matrix int[][] matrix = {{12, 10, 7, 36}, {20, 9, 8, 4}, {15, 73, 83, 13}}; // Sorting the first row Arrays.sort(matrix[0]); // Printing the result System.out.println("The matrix after sorting first row: " ); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
# declaration and initialization of 3x4 matrix matrix = [[12, 10, 7, 36], [20, 9, 8, 4], [15, 73, 83, 13]] # Sorting the first row matrix[0].sort() # Printing the result print("The matrix after sorting first row: ") for row in matrix: print(' '.join(map(str, row)))
Output
The matrix after sorting first row: 7 10 12 36 20 9 8 4 15 73 83 13
Matrix - Insertion Operation
In the insertion operation, we insert a row at the specified position of the matrix.
Algorithm
Following is an algorithm to insert a row into a given matrix at second position −
1. Start 2. Declare and initialize a matrix. 3. Define another matrix. 4. Copy the first row of original matrix to new matrix. 5. Insert the required row at second index. 6. Copy the remaining rows. 7. Print the result. 8. Stop
Example
The below example practically illustrates the insertion operation in different programming languages −
#include <stdio.h> int main() { // The original matrix int matrix[2][3] = {{19, 14, 21}, {22, 91, 81}}; // Create a new matrix with an extra row int newmatrix[3][3]; // Copy the first row of the original matrix to the new matrix for (int j = 0; j < 3; j++) { newmatrix[0][j] = matrix[0][j]; } // Adding second row to the new matrix int newRow[3] = {53, 63, 73}; for (int j = 0; j < 3; j++) { newmatrix[1][j] = newRow[j]; } // Copying the remaining rows of the original matrix to the new matrix for (int i = 2; i < 3; i++) { for (int j = 0; j < 3; j++) { newmatrix[i][j] = matrix[i - 1][j]; } } // Printing the new matrix printf("The new Matrix after adding a row: "); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%d ", newmatrix[i][j]); } printf(" "); } return 0; }
#include <iostream> #include <algorithm> using namespace std; int main() { // The original matrix int matrix[2][3] = {{19, 14, 21}, {22, 91, 81}}; // Create a new matrix with an extra row int newmatrix[3][3]; // Copy the first row of the original matrix to the new matrix copy(begin(matrix[0]), end(matrix[0]), begin(newmatrix[0])); // Adding second row to the new matrix int newRow[3] = {53, 63, 73}; copy(begin(newRow), end(newRow), begin(newmatrix[1])); // Copying the remaining rows of the original matrix to the new matrix copy(begin(matrix[1]), end(matrix[1]), begin(newmatrix[2])); // Printing the new matrix cout << "The new Matrix after adding a row: " << endl; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << newmatrix[i][j] << ' '; } cout << ' '; } return 0; }
import java.util.Arrays; public class Main { public static void main(String[] args) { // the original matrix int[][] matrix = {{19, 14, 21}, {22, 91, 81}}; // Create a new matrix with an extra row int[][] newmatrix = new int[matrix.length + 1][matrix[0].length]; // Copy the first row of the original matrix to the new matrix for (int j = 0; j < matrix[0].length; j++) { newmatrix[0][j] = matrix[0][j]; } // adding second row to the new matrix int[] newRow = {53, 63, 73}; for (int j = 0; j < newRow.length; j++) { newmatrix[1][j] = newRow[j]; } // Copying the remaining rows of the original matrix to the new matrix for (int i = 2; i < newmatrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { newmatrix[i][j] = matrix[i - 1][j]; } } // Printing the new matrix System.out.println("The new Matrix after adding a row: "); for (int i = 0; i < newmatrix.length; i++) { for (int j = 0; j < newmatrix[0].length; j++) { System.out.print(newmatrix[i][j] + " "); } System.out.println(); } } }
# The original matrix matrix = [[19, 14, 21], [22, 91, 81]] # Create a new matrix with an extra row newmatrix = matrix.copy() # Adding second row to the new matrix newRow = [53, 63, 73] newmatrix.insert(1, newRow) # Printing the new matrix print("The new Matrix after adding a row: ") for row in newmatrix: print(' '.join(map(str, row)))
Output
The new Matrix after adding a row: 19 14 21 53 63 73 22 91 81
Matrix - Deletion Operation
The deletion operation removes a particular row from the matrix.
Algorithm
Following is an algorithm to perform deletion operation on a given matrix −
1. Start 2. Declare and initialize a matrix. 3. Define another matrix. 4. Copy all elements except the row to be deleted. 5. Print the new matrix. 6. Stop
Example
Here, we see a practical implementation of deletion operation −
#include <stdio.h> // Function to delete a row from the matrix void deleteRow(int mat[3][3], int rowIndex, int rows, int cols) { // Create a new matrix with one less row int newMat[2][3]; // Copy the elements except the row to be deleted int newRow = 0; // Loop through the rows of original matrix for (int i = 0; i < rows; i++) { // Skip the row to be deleted if (i != rowIndex) { // Loop through the cols of original matrix for (int j = 0; j < cols; j++) { // Copy the element from mat to newMat newMat[newRow][j] = mat[i][j]; } newRow++; // Increment the row index } } // Print the new matrix printf("The new Matrix after deleting a row: "); for (int i = 0; i < 2; i++) { for (int j = 0; j < cols; j++) { printf("%d ", newMat[i][j]); } printf(" "); } } int main() { // The original matrix int matrix[3][3] = {{19, 14, 21}, {53, 63, 73}, {22, 91, 81}}; // Delete the first row deleteRow(matrix, 0, 3, 3); return 0; }
#include <iostream> using namespace std; // Function to delete a row from the matrix void deleteRow(int mat[3][3], int rowIndex, int rows, int cols) { // Create a new matrix with one less row int newMat[2][3]; // Copy the elements except the row to be deleted int newRow = 0; // Loop through the rows of original matrix for (int i = 0; i < rows; i++) { // Skip the row to be deleted if (i != rowIndex) { // Loop through the cols of original matrix for (int j = 0; j < cols; j++) { // Copy the element from mat to newMat newMat[newRow][j] = mat[i][j]; } newRow++; // Increment the row index } } // Print the new matrix cout << "The new Matrix after deleting a row: "; for (int i = 0; i < 2; i++) { for (int j = 0; j < cols; j++) { cout << newMat[i][j] << ' '; } cout << ' '; } } int main() { // The original matrix int matrix[3][3] = {{19, 14, 21}, {53, 63, 73}, {22, 91, 81}}; // Delete the first row deleteRow(matrix, 0, 3, 3); return 0; }
import java.util.Arrays; public class Main { // method to delete row public static int[][] deleteRow(int[][] mat, int rowIndex) { // get the number of rows and columns int rows = mat.length; int cols = mat[0].length; // create a new matrix with one less row int[][] newMat = new int[rows - 1][cols]; // copy the elements except the row to be deleted int newRow = 0; // loop through the rows of original matrix for (int i = 0; i < rows; i++) { // skip the row to be deleted if (i != rowIndex) { // loop through the cols of original matrix for (int j = 0; j < cols; j++) { // copy the element from mat to newMat newMat[newRow][j] = mat[i][j]; } newRow++; // increment the row index } } // return the new matrix return newMat; } public static void main(String[] args) { // the original matrix int[][] matrix = {{19, 14, 21}, {53, 63, 73}, {22, 91, 81}}; // delete the first row int[][] newmatrix = deleteRow(matrix, 0); // Printing the new matrix System.out.println("The new Matrix after deleting a row: "); for (int i = 0; i < newmatrix.length; i++) { for (int j = 0; j < newmatrix[0].length; j++) { System.out.print(newmatrix[i][j] + " "); } System.out.println(); } } }
# The original matrix matrix = [[19, 14, 21], [53, 63, 73], [22, 91, 81]] # Delete the first row newmatrix = matrix[1:] # Printing the new matrix print("The new Matrix after deleting a row: ") for row in newmatrix: print(' '.join(map(str, row)))
Output
The new Matrix after deleting a row: 53 63 73 22 91 81