Matrix operations using operator overloading
Last Updated :
27 Apr, 2023
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
Rules for operator overloading In C++, following are the general rules for the things that are not allowed with operator overloading. 1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed. 4) O
3 min read
Operator Overloading in C++ in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
Overloading stream insertion (<>) operators in C++ In C++, stream insertion operator "<<" is used for output and extraction operator ">>" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be
2 min read
C++ Bitwise Operator Overloading Prerequisites: Operator OverloadingBitwise Operator in C/C++ In C++, there are a total of six bitwise operators. The six bitwise operators are bitwise AND (&), bitwise OR (|), bitwise XOR (^), left shift (<<), right shift (>>), and bitwise NOT (~). The & (bitwise AND) in C++ take
7 min read
Types of Operator Overloading in C++ C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change some specific operators' functions to do different tasks.Syntax: Return_Type classname :: op
4 min read
Different Ways of Operator Overloading in C++ In C++, operator overloading is the concept that allows us to redefine the behavior of the already existing operator for our class. C++ provides a special function called operator function that can be used to achieve operator overloading. In this article, we will learn the different ways in which we
6 min read
Typecast Operator Overloading in C++ In C++, the typecast operator can be overloaded to customize the behavior of casting operators to define how user-defined data types can be converted into other types. This enables developers to define how instances of a class are converted to other types, providing more control over implicit type c
6 min read
Overloading Subscript or array index operator [] in C++ The Subscript or Array Index Operator is denoted by '[]'. This operator is generally used with arrays to retrieve and manipulate the array elements. This is a binary or n-ary operator and is represented in two parts: Postfix/Primary ExpressionExpressionThe postfix expression, also known as the prima
6 min read
C++ Logical (&&, ||, !) Operator Overloading Prerequisites: OperatorsOperator Overloading Logical operators are used for combining two or more conditions or constraints or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false. In C++, there are 3 logical operators: Logi
3 min read
C++ Assignment Operator Overloading Prerequisite: Operator OverloadingThe assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types.Assignment operator overloading is binary operator overloading.Overloading ass
4 min read