Matrix Arithmetic
Learn how to overload the arithmetic operators in C++.
In this lesson, we’ll learn how to enable arithmetic operations using Matrix
objects. To make these operations possible, we need to overload the operators.
Addition (+
)
Let’s consider a scenario where we’re not familiar with objects, and we have two matrices, m1
and m2
. Our objective is to perform the sum of these matrices. Without objects, we would typically achieve this by iterating through each element of m1
and m2
using nested loops and adding the corresponding elements together.
Now, let’s explore an alternative approach using objects. What if we create two objects, m1
and m2
, and want to perform the matrix summation?
Take a look at the following code:
Matrix& m1 = Ms[0], & m2 = Ms[1];
Matrix sum = m1+m2; // Will this work?
Will the second line execute?
We have provided the above scenario in the editor below. Run it and see what happens.
Run the code below after uncommenting lines 11–13. We’ve deliberately hidden the Matrix.h
and Matrix.cpp
implementation.
3 2 2 1 2 4 5 2 2 7 8 2 2 5 3 4 6 5 3 3 4 5 8 9 4 5 3 7 2 3
Let’s proceed with the implementation of arithmetic operations.
Before we begin implementing these operations, let’s review some important points for addition/subtraction.
It’s essential that both operands (which are objects of the type
Matrix
) have the same size. This means that the number of rows and columns in both matrices must be equal. During the operation, each element in the left matrix will be either added or subtracted from its corresponding element in the right matrix, creating a new matrix as a result.
Take a look at this addition illustration for a visual representation.
Furthermore, we have two types of implementations that overload the +
operator:
-
Matrix addition
-
Scalar addition
Matrix addition
In this type of addition, we’ll add two matrices. Our overloaded +
operator will have the following signature:
const Matrix operator+(const Matrix& M)const;
We have added the above prototype in the Matrix.h
file.
This will have the following implementation:
const Matrix Matrix::operator+(const Matrix& M)const{if (this->rows != M.rows || this->cols != M.cols){cout << "Addition of the two matrices is not possible as there dimensions are different.Returning the first Matrix as result. Press any key to continue" << endl;return *this;}Matrix result(M.rows,M.cols);for (int r = 0; r < this->rows; r++){for (int c = 0; c < this->cols; c++){result.Vs[r][c] = this->Vs[r][c] + M.Vs[r][c];}}return result;}
Lines 3–7: Here, we check if the rows and columns of both matrices are equal.
Line 8: Here, we declare a
Matrix
class objectresult
to store the result of the addition.Lines 9–15: We use nested
for
loops to perform subtraction.Line 16: We return the
result
matrix.
Tip: We have added the above implementation in the
Matrix.cpp
file for you, now uncomment lines 15–37 frommain.cpp
to see its impact and implement your code inMatrix.cpp
file.
Exercise playground
Let’s execute the code provided below to verify the correctness of our addition implementation.
3 2 2 1 2 4 5 2 2 7 8 2 2 5 3 4 6 5 3 3 4 5 8 9 4 5 3 7 2 3
Scalar addition
Scalar matrix addition refers to the operation of adding a scalar value to every element of a matrix. In this operation, a scalar value (a single number) is added to each element in the matrix, resulting in a new matrix with the same dimensions.
To implement this, we’ll again overload the +
operator with the following signature:
const Matrix operator+(const int s)const;
This will have the following implementation:
const Matrix Matrix::operator+(const int s)const{Matrix result(this->rows, this->cols);for (int r = 0; r < this->rows; r++){for (int c = 0; c < this->cols; c++){result.Vs[r][c] = this->Vs[r][c]+s;}}return result;}
Line 3: We create a new
result
matrix to store results.Lines 4–10: We use nested
for
loops to add the scalar value ofs
to each element of the matrix.
Tip: Test your implementation in the Exercise playground.
Subtraction (-
)
Similar to addition, subtraction has two types of implementations that overload the -
operator:
-
Matrix subtraction
-
Scalar subtraction
Matrix subtraction
The matrix subtraction function operates in a similar manner to the matrix addition function we covered earlier. We only need to make a few minor adjustments in the code. Give it a try and implement it yourself.
Tip: Test your implementation in the Exercise playground.
Scalar subtraction
The scalar subtraction function operates in a similar manner to the scalar addition function we covered earlier. We only need to make a few minor adjustments in the code. Give it a try and implement it yourself.
Tip: Test your implementation in the Exercise playground.
If you have trouble getting to the solution, you can click the “Show Solution” button to see how to implement it.
Multiplication (*
)
Let’s explore matrix multiplication.
Matrix multiplication
For multiplication (*
) , the number of columns of the left matrix must equal the number of rows of the right matrix. To generate the resultant matrix, we will do the following:
In the above image, you can observe the complete process of matrix multiplication. It illustrates how each row of matrix and each column of matrix are multiplied together to produce the resulting matrix . This multiplication process is performed for every combination of rows and columns, resulting in the complete matrix .
Let’s move toward the implementation of matrix multiplication:
const Matrix Matrix::operator*(const Matrix& M)const{if (this->cols != M.rows){cout << "Multiplication not possible with the provided matrices.\n";cout << "Returning the first matrix as default. " << endl;return *this;}Matrix result(this->rows, M.cols);for (int r = 0; r < result.rows; r++){for (int c = 0; c < result.cols; c++){int ans = 0;for (int n = 0; n < this->cols; n++){ans += this->Vs[r][n]*M.Vs[n][c];}result.Vs[r][c] = ans;}}return result;}
The code snippet represents the matrix multiplication operation implemented in the Matrix
class. Matrix multiplication requires three nested loops to perform the calculation accurately.
The outer two loops, on lines 10 and 12, iterate over the rows and columns of the resulting matrix, respectively. These loops are responsible for accessing each element of the resulting matrix to compute its value.
The innermost loop is used to perform the dot product calculation between corresponding elements of the current row in the first matrix (
this
) and the current column in the second matrix (M
). The loop iterates over the columns of the first matrix and the rows of the second matrix. The loop variablen
is used as the index to access the elements in both matrices.Within this loop, the dot product of the corresponding row and column elements is calculated by multiplying the elements from the first matrix (
this->Vs[r][n]
) and the second matrix (M.Vs[n][c]
). The product is then added to the running sum (ans
).After the innermost loop completes, the computed dot product (
ans
) is stored in the resulting matrix at the corresponding row and column (result.Vs[r][c]
).By iterating over the rows and columns of the resulting matrix and performing the dot product calculation for each element, the code accurately computes the matrix multiplication and populates the resulting matrix.
If the dimensions of the matrices are incompatible with multiplication (the number of columns in the first matrix does not match the number of rows in the second matrix), an error message is displayed, and the function returns the first matrix as a default result (
*this
).
The three nested for
loops enable the code to perform the necessary computations to multiply two matrices and produce the resulting matrix.
Scalar multiplication
Now that we have covered the multiplication of two matrices and discussed scalar matrix addition and subtraction, it’s time to put your skills to the test. Your task is to write a code for scalar matrix operations in the above implementation.
Tip: Test your implementation in the Exercise playground.
If you have trouble getting to the solution, you can click the “Show Solution” button to see how to implement it.
.