1 Crore+ students have signed up on EduRev. Have you? 
The addition of two matrices A_{m * n} and B_{m * n }gives a matrix C_{m * n}. The elements of C are sum of corresponding elements in A and B which can be shown as:
The algorithm for addition of matrices can be written as:
for i in 1 to m
for j in 1 to n
c_{ij} = a_{ij }+ b_{ij}
// C++ Program for matrix addition
#include <iostream>
using namespace std;
int main()
{
int n = 2, m = 2;
int a[n][m] = { { 2, 5 }, { 1, 7 } };
int b[n][m] = { { 3, 7 }, { 2, 9 } };
int c[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << c[i][j] << " ";
cout << endl;
}
}
Output:
5 12
3 16
Time Complexity: O(n * m)
Auxiliary Space: O(n * m)
Key points:
The subtraction of two matrices A_{m * n} and B_{m * n} gives a matrix C_{m * n}. The elements of C are difference of corresponding elements in A and B which can be represented as:
The algorithm for subtraction of matrices can be written as:
for i in 1 to m
for j in 1 to n
c_{ij} = a_{ij}b_{ij}
// C++ Program for matrix substraction
#include <iostream>
using namespace std;
int main()
{
int n = 2, m = 2;
int a[n][m] = { { 2, 5 }, { 1, 7 } };
int b[n][m] = { { 3, 7 }, { 2, 9 } };
int c[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
c[i][j] = a[i][j]  b[i][j];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << c[i][j] << " ";
cout << endl;
}
}
Output:
1 2
1 2
Key points:
The multiplication of two matrices A_{m * n} and B_{n * p} gives a matrix C_{m * p}. It means number of columns in A must be equal to number of rows in B to calculate C = A * B. To calculate element c11, multiply elements of 1st row of A with 1st column of B and add them (5 * 1 + 6 * 4) which can be shown as:
The algorithm for multiplication of matrices A with order m*n and B with order n*p can be written as:
for i in 1 to m
for j in 1 to p
c_{ij} = 0
for k in 1 to n
c_{ij} + = a_{ik }* b_{kj}
// C++ Program for matrix Multiplication
#include <iostream>
using namespace std;
int main()
{
int n = 2, m = 2;
int a[n][m] = { { 2, 5 }, { 1, 7 } };
int b[n][m] = { { 3, 7 }, { 2, 9 } };
int c[n][m];
int i, j, k;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
c[i][j] = 0;
for (k = 0; k < n; k++)
c[i][j] += a[i][k] * b[k][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << c[i][j] << " ";
cout << endl;
}
}
Output:
16 59
17 70
Key points:
45 videos55 docs21 tests
