Adding two matrices

Tags : matrix, geeksforgeeks, cpp, easy

The Addition is one of the easiest operations to carry out. The same holds true for matrices. Two matrices can be added only if they have the same dimensions. The elements at similar positions get added.

Given two matrices A and B having (n1 x m1) and (n2 x m2) dimensions respectively. Add A and B.

Your Task: You don’t need to read input or print anything. Complete the function sumMatrix() that takes A and B as input parameters and returns a matrix containing their sum. If the addition is not possible return an empty matrix (of size zero).

Expected Time Complexity: O(n*m)
Expected Auxiliary Space: O(n*m)

Examples #

Example 1:

Input:
n1 = 2, m1 = 3
A[][] = [[1, 2, 3], [4, 5, 6]]

n2 = 2, m2 = 3
B[][] = [[1, 3, 3], [2, 3, 3]]

Output: 2 5 6 6 8 9
Explanation:
The summation matrix of A and B is:
res[][] = [[2, 5, 6], [6, 8, 9]]
The output is generated by traversing each
row sequentially.

Example 2:

Input:
n1 = 3, m1 = 2
A[][] = [[1, 2], [3, 4],  [5, 6]]

n2 = 3, m2 = 2
B[][] = [[1, 3], [3, 2], [3, 3]]
Output: 2 5 6 6 8 9

Constraints #

Solutions #

class Solution{
    public:
    //Function to add two matrices.
    vector<vector<int> > sumMatrix( const vector<vector<int> >& A, const vector<vector<int> >& B)
    {
        // code here
        int m = A.size(), n = A[0].size();
        int m2 = B.size(), n2 = B[0].size();
        vector<vector<int>> v;
        if( m != m2 || n != n2 )
            return v; 
        
        for(int i=0; i<m; i++){
            vector<int> temp(n);
            for(int j=0; j<n; j++)
                temp[j] = A[i][j] + B[i][j];
            v.push_back(temp);
        }

        return v;
    }

};