Addition of Matrices
The addition of two matrices, Xm*n and Ym*n, gives a resultant matrix Zm*n. The elements in the resulting matrix Z is the addition of the corresponding elements of two matrices.
Algorithm
The algorithm for the addition of two matrices can be described as
for i in 1 to m
for j in 1 to n
zij = xij + yij
Program
// C++ Program for matrix addition
#include <iostream>
using namespace std;
int main()
{
int n = 2, m = 2;
int y[n][m] = { { 3, 2 }, { 2, 3 } };
int z[n][m] = { { 1, 2 }, { 2, 1 } };
int x[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
z[i][j] = x[i][j] + y[i][j];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << z[i][j] << " ";
cout << endl;
}
}
Output:
4 4
4 4
Time Complexity: O(n * m)
Auxiliary Space: O(n * m)
Subtraction of Matrices
The subtraction of two matrices, Xm*n and Ym*n, gives a resultant matrix Zm*n. The elements in the resulting matrix Z is the subtraction of the corresponding elements of two matrices.
Algorithm
The algorithm for the subtraction of two matrices can be described as
for i in 1 to m
for j in 1 to n
zij = xij-yij
Program
// C++ Program for matrix subtraction
#include <iostream>
using namespace std;
int main()
{
int n = 2, m = 2;
int x[n][m] = { { 4, 8 }, { 3, 8 } };
int y[n][m] = { { 3, 6 }, { 2, 1 } };
int z[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
z[i][j] = x[i][j] - y[i][j];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << z[i][j] << " ";
cout << endl;
}
}
Output:
1 2
1 7