Given two square matrices, a[][] and b[][], each of size n x n. The task is to compute the sum of these two matrices and store the result in the matrix a[][] itself.

Examples:
Input: a[][] = [[1, 2], [3, 4]], b[][] = [[4, 3], [2, 1]]
Output: [[5, 5], [5, 5]]
Explanation: The result will be: [[5, 5], [5, 5]] after adding the corresponding elements of both matrices.
Input: a[][] = [[7, 8], [9, 10]], b[][] = [[1, 2], [3, 4]]
Output: [[8, 10], [12, 14]]
Explanation: The result will be [[8, 10], [12, 14]] after adding the corresponding elements of both matrices.
Using In-Place Matrix Addition - O(n ^ 2) Time and O(1) Space
The idea is to perform the addition in-place. Since the answer needs to be stored in the first matrix itself, each element of the first matrix is directly updated by adding the corresponding element from the second matrix.
Working of Approach:
- Traverse both matrices simultaneously using two nested loops, where the outer loop iterates through the rows and the inner loop iterates through the columns.
- For each cell (i, j), access the corresponding elements a[i][j] and b[i][j].
- Add the value of b[i][j] directly to a[i][j], storing the result in the first matrix itself.
- Continue this process until every element of the matrices has been processed exactly once.
- After the traversal completes, the matrix a contains the sum of the two matrices.
Let us understand with an example:
- Initially, a = [[7, 8], [9, 10]] and b = [[1, 2], [3, 4]].
- At (0, 0), add 7 + 1 = 8; at (0, 1), add 8 + 2 = 10. Now a = [[8, 10], [9, 10]].
- Move to the second row. At (1, 0), add 9 + 3 = 12; at (1, 1), add 10 + 4 = 14.
- After processing all the elements, the first matrix becomes [[8, 10], [12, 14]].
- This updated matrix a is the required sum of the two given matrices.
#include <iostream>
#include <vector>
using namespace std;
// Function to perform matrix addition.
void addMat(vector<vector<int>> &a, vector<vector<int>> &b)
{
// iterating over each row and column of the matrices.
for (int i = 0; i < a.size(); i++)
{
for (int j = 0; j < a[0].size(); j++)
// adding corresponding elements of both matrices.
a[i][j] += b[i][j];
}
}
int main()
{
vector<vector<int>> a = {{7, 8}, {9, 10}};
vector<vector<int>> b = {{1, 2}, {3, 4}};
addMat(a, b);
cout << "[";
for (int i = 0; i < a.size(); i++)
{
cout << "[";
for (int j = 0; j < a[i].size(); j++)
{
cout << a[i][j];
if (j != a[i].size() - 1)
cout << ", ";
}
cout << "]";
if (i != a.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
import java.util.*;
class GFG {
// Function to perform matrix addition.
static void addMat(int[][] a, int[][] b)
{
// iterating over each row and column of the
// matrices.
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++)
// adding corresponding elements of both
// matrices.
a[i][j] += b[i][j];
}
}
public static void main(String[] args)
{
int[][] a = { { 7, 8 }, { 9, 10 } };
int[][] b = { { 1, 2 }, { 3, 4 } };
addMat(a, b);
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print("[");
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j]);
if (j != a[i].length - 1)
System.out.print(", ");
}
System.out.print("]");
if (i != a.length - 1)
System.out.print(", ");
}
System.out.print("]");
}
}
def addMat(a, b):
# iterating over each row and column of the matrices.
for i in range(len(a)):
for j in range(len(a[0])):
# adding corresponding elements of both matrices.
a[i][j] += b[i][j]
if __name__ == "__main__":
a = [[7, 8], [9, 10]]
b = [[1, 2], [3, 4]]
addMat(a, b)
print('[')
for i in range(len(a)):
print('[', end='')
for j in range(len(a[i])):
print(a[i][j], end='')
if j != len(a[i]) - 1:
print(', ', end='')
print(']')
if i != len(a) - 1:
print(', ', end='')
print(']')
using System;
using System.Collections.Generic;
class GFG {
// Function to perform matrix addition.
static void addMat(List<List<int> > a,
List<List<int> > b)
{
// iterating over each row and column of the
// matrices.
for (int i = 0; i < a.Count; i++) {
for (int j = 0; j < a[0].Count; j++)
// adding corresponding elements of both
// matrices.
a[i][j] += b[i][j];
}
}
static void Main()
{
List<List<int> > a = new List<List<int> >{
new List<int>{ 7, 8 }, new List<int>{ 9, 10 }
};
List<List<int> > b
= new List<List<int> >{ new List<int>{ 1, 2 },
new List<int>{ 3, 4 } };
addMat(a, b);
Console.Write("[");
for (int i = 0; i < a.Count; i++) {
Console.Write("[");
for (int j = 0; j < a[i].Count; j++) {
Console.Write(a[i][j]);
if (j != a[i].Count - 1)
Console.Write(", ");
}
Console.Write("]");
if (i != a.Count - 1)
Console.Write(", ");
}
Console.Write("]");
}
}
function addMat(a, b)
{
// iterating over each row and column of the matrices.
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < a[0].length; j++) {
// adding corresponding elements of both
// matrices.
a[i][j] += b[i][j];
}
}
}
// Driver Code
let a = [ [ 7, 8 ], [ 9, 10 ] ];
let b = [ [ 1, 2 ], [ 3, 4 ] ];
addMat(a, b);
console.log("[");
for (let i = 0; i < a.length; i++) {
console.log("[");
for (let j = 0; j < a[i].length; j++) {
console.log(a[i][j]);
if (j != a[i].length - 1)
console.log(", ");
}
console.log("]");
if (i != a.length - 1)
console.log(", ");
}
console.log("]");
Output
[[8, 10], [12, 14]]