Matrix operations using operator overloading
Last Updated :
15 Jul, 2025
Pre-requisite: Operator Overloading
Given two matrix mat1[][] and mat2[][] of NxN dimensions, the task is to perform Matrix Operations using Operator Overloading.
Examples:
Input: arr1[][] = { {1, 2, 3}, {4, 5, 6}, {1, 2, 3}}, arr2[][] = { {1, 2, 3}, {4, 5, 16}, {1, 2, 3}}
Output:
Addition of two given Matrices is:
2 4 6
8 10 22
2 4 6
Subtraction of two given Matrices is:
0 0 0
0 0 -10
0 0 0
Multiplication of two given Matrices is:
12 18 44
30 45 110
12 18 44
Input: arr1[][] = { {11, 2, 3}, {4, 5, 0}, {1, 12, 3}}, arr2[][] = { {1, 2, 3}, {41, 5, 16}, {1, 22, 3}}
Output:
Addition of two given Matrices is :
12 4 6
45 10 16
2 34 6
Subtraction of two given Matrices is :
10 0 0
-37 0 -16
0 -10 0
Multiplication of two given Matrices is :
96 98 74
209 33 92
496 128 204
Approach:
To overload +, -, * operators, we will create a class named matrix and then make a public function to overload the operators.
- To overload operator '+' use prototype:
Return_Type classname :: operator +(Argument list)
{
// Function Body
}
Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 + M2.
In the above statement M1 is treated as global and M2[][] is passed as an argument to the function "void Matrix::operator+(Matrix x)".
In the above overloaded function, the approach for addition of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments).
- To overload operator '-' use prototype:
Return_Type classname :: operator -(Argument list)
{
// Function Body
}
Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 - M2
In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function "void Matrix::operator-(Matrix x)".
In the above overloaded function, the approach for subtraction of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments).
- To overload operator '*' use prototype:
Return_Type classname :: operator *(Argument list)
{
// Function Body
}
Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 * M2.
In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function "void Matrix::operator*(Matrix x)".
In the above overloaded function, the approach for multiplication of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments).
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include "bits/stdc++.h"
#define rows 50
#define cols 50
using namespace std;
int N;
// Class for Matrix operator overloading
class Matrix {
// For input Matrix
int arr[rows][cols];
public:
// Function to take input to arr[][]
void input(vector<vector<int> >& A);
void display();
// Functions for operator overloading
void operator+(Matrix x);
void operator-(Matrix x);
void operator*(Matrix x);
};
// Functions to get input to Matrix
// array arr[][]
void Matrix::input(vector<vector<int> >& A)
{
// Traverse the vector A[][]
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
arr[i][j] = A[i][j];
}
}
}
// Function to display the element
// of Matrix
void Matrix::display()
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
cout << arr[i][j] << ' ';
}
cout << endl;
}
}
// Function for addition of two Matrix
// using operator overloading
void Matrix::operator+(Matrix x)
{
// To store the sum of Matrices
int mat[N][N];
// Traverse the Matrix x
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Add the corresponding
// blocks of Matrices
mat[i][j] = arr[i][j]
+ x.arr[i][j];
}
}
// Display the sum of Matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
cout << mat[i][j] << ' ';
}
cout << endl;
}
}
// Function for subtraction of two Matrix
// using operator overloading
void Matrix::operator-(Matrix x)
{
// To store the difference of Matrices
int mat[N][N];
// Traverse the Matrix x
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Subtract the corresponding
// blocks of Matrices
mat[i][j] = arr[i][j]
- x.arr[i][j];
}
}
// Display the difference of Matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
cout << mat[i][j] << ' ';
}
cout << endl;
}
}
// Function for multiplication of
// two Matrix using operator
// overloading
void Matrix::operator*(Matrix x)
{
// To store the multiplication
// of Matrices
int mat[N][N];
// Traverse the Matrix x
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Initialise current block
// with value zero
mat[i][j] = 0;
for (int k = 0; k < N; k++) {
mat[i][j] += arr[i][k]
* (x.arr[k][j]);
}
}
}
// Display the multiplication
// of Matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
cout << mat[i][j] << ' ';
}
cout << endl;
}
}
// Driver Code
int main()
{
// Dimension of Matrix
N = 3;
vector<vector<int> > arr1
= { { 1, 2, 3 },
{ 4, 5, 6 },
{ 1, 2, 3 } };
vector<vector<int> > arr2
= { { 1, 2, 3 },
{ 4, 5, 16 },
{ 1, 2, 3 } };
// Declare Matrices
Matrix mat1, mat2;
// Take Input to matrix mat1
mat1.input(arr1);
// Take Input to matrix mat2
mat2.input(arr2);
// For addition of matrix
cout << "Addition of two given"
<< " Matrices is : \n";
mat1 + mat2;
// For subtraction of matrix
cout << "Subtraction of two given"
<< " Matrices is : \n";
mat1 - mat2;
// For multiplication of matrix
cout << "Multiplication of two"
<< " given Matrices is : \n";
mat1* mat2;
return 0;
}
Java
import java.util.*;
public class Matrix {
int arr[][];
int N;
// Constructor to initialize
// Matrix object
public Matrix(int n)
{
N = n;
arr = new int[N][N];
}
// Function to take input to arr[][]
void input(List<List<Integer> > A)
{
// Traverse the List A[][]
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
arr[i][j] = A.get(i).get(j);
}
}
}
// Function to display the element of Matrix
void display()
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
// Function for addition of two Matrix using operator
// overloading
void add(Matrix x)
{
// To store the sum of Matrices
int mat[][] = new int[N][N];
// Traverse the Matrix x
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Add the corresponding blocks of Matrices
mat[i][j] = arr[i][j] + x.arr[i][j];
}
}
// Display the sum of Matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
// Function for subtraction of two Matrix using operator
// overloading
void subtract(Matrix x)
{
// To store the difference of Matrices
int mat[][] = new int[N][N];
// Traverse the Matrix x
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Subtract the corresponding blocks of
// Matrices
mat[i][j] = arr[i][j] - x.arr[i][j];
}
}
// Display the difference of Matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
// Function for multiplication of two Matrix using
// operator overloading
public void multiply(Matrix x)
{
// To store the multiplication
// of Matrices
int[][] mat = new int[N][N];
// Traverse the Matrix x
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Initialise current block
// with value zero
mat[i][j] = 0;
for (int k = 0; k < N; k++) {
mat[i][j] += arr[i][k] * (x.arr[k][j]);
}
}
}
// Display the multiplication
// of Matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print the element
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
// Driver Code
public static void main(String[] args)
{
// Dimension of Matrix
int N = 3;
List<List<Integer> > arr1 = Arrays.asList(
Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6),
Arrays.asList(1, 2, 3));
List<List<Integer> > arr2 = Arrays.asList(
Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 16),
Arrays.asList(1, 2, 3));
// Declare Matrices
Matrix mat1 = new Matrix(N);
Matrix mat2 = new Matrix(N);
// Take Input to matrix mat1
mat1.input(arr1);
// Take Input to matrix mat2
mat2.input(arr2);
// For addition of matrix
System.out.println(
"Addition of two given Matrices is : ");
mat1.add(mat2);
// For subtraction of matrix
System.out.println(
"Subtraction of two given Matrices is : ");
mat1.subtract(mat2);
// For multiplication of matrix
System.out.println(
"Multiplication of two given Matrices is : ");
mat1.multiply(mat2);
}
}
Python3
# Python program for the above approach
# Dimension of Matrix
N = 3
rows = 50
cols = 50
# Class for Matrix operator overloading
class Matrix:
def __init__(self):
# For input Matrix
self.arr = [[0 for i in range(cols)] for j in range(rows)]
# Functions to get input to Matrix
# array arr[][]
def input(self, A):
# Traverse the vector A[][]
for i in range(N):
for j in range(N):
self.arr[i][j] = A[i][j]
# Function to display the element
# of Matrix
def display(self):
for i in range(N):
for j in range(N):
# Print the element
print(self.arr[i][j], end=' ')
print()
# Function for addition of two Matrix
# using operator overloading
def __add__(self, x):
# To store the sum of Matrices
mat = [[0 for i in range(N)] for j in range(N)]
for i in range(N):
for j in range(N):
# Add the corresponding
# blocks of Matrices
mat[i][j] = self.arr[i][j] + x.arr[i][j]
# Display the sum of Matrices
for i in range(N):
for j in range(N):
# Print the element
print(mat[i][j], end=' ')
print()
# Function for subtraction of two Matrix
# using operator overloading
def __sub__(self, x):
# To store the difference of Matrices
mat = [[0 for i in range(N)] for j in range(N)]
# Traverse the Matrix x
for i in range(N):
for j in range(N):
# Subtract the corresponding
# blocks of Matrices
mat[i][j] = self.arr[i][j] - x.arr[i][j]
# Display the difference of Matrices
for i in range(N):
for j in range(N):
# Print the element
print(mat[i][j], end=' ')
print()
# Function for multiplication of
# two Matrix using operator
# overloading
def __mul__(self, x):
# To store the multiplication
# of Matrices
mat = [[0 for i in range(N)] for j in range(N)]
# Traverse the Matrix x
for i in range(N):
for j in range(N):
# Initialise current block
# with value zero
mat[i][j] = 0
for k in range(N):
mat[i][j] += self.arr[i][k] * (x.arr[k][j])
# Display the multiplication
# of Matrices
for i in range(N):
for j in range(N):
# Print the element
print(mat[i][j], end=' ')
print()
# Driver Code
arr1 = [[1, 2, 3],
[4, 5, 6],
[1, 2, 3]]
arr2 = [[1, 2, 3],
[4, 5, 16],
[1, 2, 3]]
# Declare Matrices
mat1 = Matrix()
mat2 = Matrix()
# Take Input to matrix mat1
mat1.input(arr1)
# Take Input to matrix mat2
mat2.input(arr2)
# For addition of matrix
print("Addition of two given Matrices is : ")
mat1 + mat2
# For subtraction of matrix
print("Subtraction of two given Matrices is : ")
mat1 - mat2
# For multiplication of matrix
print("Multiplication of two given Matrices is : ")
mat1 * mat2
JavaScript
function matrixAddition(matrix1, matrix2) {
var result = [];
for (var i = 0; i < matrix1.length; i++) {
var row = [];
for (var j = 0; j < matrix1[i].length; j++) {
row.push(matrix1[i][j] + matrix2[i][j]);
}
result.push(row.join(" "));
}
return result.join("\n");
}
function matrixSubtraction(matrix1, matrix2) {
var result = [];
for (var i = 0; i < matrix1.length; i++) {
var row = [];
for (var j = 0; j < matrix1[i].length; j++) {
row.push(matrix1[i][j] - matrix2[i][j]);
}
result.push(row.join(" "));
}
return result.join("\n");
}
function matrixMultiplication(matrix1, matrix2) {
var result = [];
for (var i = 0; i < matrix1.length; i++) {
var row = [];
for (var j = 0; j < matrix2[0].length; j++) {
var sum = 0;
for (var k = 0; k < matrix1[0].length; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
row.push(sum);
}
result.push(row.join(" "));
}
return result.join("\n");
}
var matrix1 = [
[1, 2, 3],
[4, 5, 6],
[1, 2, 3]
];
var matrix2 = [
[1, 2, 3],
[4, 5, 16],
[1, 2, 3]
];
console.log("Addition of two given Matrices is: ");
console.log(matrixAddition(matrix1, matrix2));
console.log("\n");
console.log("Subtraction of two given Matrices is: ");
console.log(matrixSubtraction(matrix1, matrix2));
console.log("\n");
console.log("Multiplication of two given Matrices is: ");
console.log(matrixMultiplication(matrix1, matrix2));
console.log("\n");
OutputAddition of two given Matrices is :
2 4 6
8 10 22
2 4 6
Subtraction of two given Matrices is :
0 0 0
0 0 -10
0 0 0
Multiplication of two given Matrices is :
12 18 44
30 45 110
12 18 44
Time Complexity:
The time complexity of the input() function is O(N^2) because it has to traverse the entire input matrix/vector of size NxN.
The time complexity of the display() function is also O(N^2) because it has to print all the elements of the matrix/vector.
The time complexity of the operator overloading functions for addition, subtraction, and multiplication of two matrices is O(N^3) because for each element in the output matrix, we need to calculate the sum/difference/product of N elements from the input matrices.
Therefore, the overall time complexity of the program is O(N^3) for each operator overload.
Auxiliary Space: O(N^2) because we need to store two matrices of size NxN in memory, which takes up O(N^2) space.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem