Overload Addition Operator to Add Two Matrices in C++



Suppose we have two matrices mat1 and mat2. We shall have to add these two matrices and form the third matrix. We shall have to do this by overloading the addition operator.

So, if the input is like

5 8
9 6
7 9


8 3
4 7
6 3

then the output will be

13 11
13 13
13 12

To solve this, we will follow these steps −

  • Overload the addition operator, this will take another matrix mat as second argument

  • define one blank 2d array vv

  • Define one 2D array vv and load current matrix elements into it

  • for initialize i := 0, when i < size of vv, update (increase i by 1), do:

    • for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:

      • vv[i, j] := vv[i, j] + mat.a[i, j]
  • return a new matrix using vv

Let us see the following implementation to get better understanding −

Example

#include <iostream>
#include <vector>
using namespace std;
class Matrix {
  public:
    Matrix() {}
    Matrix(const Matrix& x) : a(x.a) {}
    Matrix(const vector<vector<int>>& v) : a(v) {}
    Matrix operator+(const Matrix&);
    vector<vector<int>> a;
    void display(){
        for(int i = 0; i<a.size(); i++){
            for(int j = 0; j<a[i].size(); j++){
                cout << a[i][j] << " ";
            }    
            cout << endl;
        }
    }
};
Matrix Matrix::operator+(const Matrix& m){
    vector<vector<int>> vv = a;
    for (int i=0; i<vv.size(); i++){
        for (int j=0; j<vv[0].size(); j++){
            vv[i][j] += m.a[i][j];
        }
    }
    return Matrix(vv);
}
int main(){
   vector<vector<int>> mat1 = {{5,8},{9,6},{7,9}};
   vector<vector<int>> mat2 = {{8,3},{4,7},{6,3}};
   int r = mat1.size();
   int c = mat1[0].size();
   Matrix m1(mat1), m2(mat2), res;
   res = m1 + m2;
   res.display();
}

Input

{{5,8},{9,6},{7,9}}, {{8,3},{4,7},{6,3}}

Output

13 11
13 13
13 12
Updated on: 2021-10-07T08:48:02+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements