Javatpoint Logo
Javatpoint Logo

Program to calculate the subtraction of 2 matrices

Explanation

In this program, we need to subtract two matrices and print the resulting matrix.

Subtraction of two matrices:

Matrix B can be subtracted from matrix A or vice versa if and only if they have same dimensions that are, the same number of rows and columns. It is not possible to subtract a 2 3 matrix from a 3 2 matrix. Subtraction of two matrices can be performed by subtracting their corresponding elements as

Program to calculate the subtraction of 2 matrices

Subtraction of two matrices can be performed by looping through the first and second matrix. Calculating the difference between their corresponding elements and store the result in the third matrix.

Algorithm

  1. Declare and initialize two two-dimensional arrays a and b.
  2. Calculate the number of rows and columns present in the array a (as dimensions of both the arrays are same) and store it in variables rows and cols respectively.
  3. Declare another array diff with dimensions present in rows and columns.
  4. Loop through the arrays a and b, calculate the difference between the corresponding elements
    e.g a11 - b11 = diff11
  5. Display the elements of array diff.

Solution

Python

Output:

Subtraction of two matrices: 
2 5 3 
1 1 0 
0 1 2 

C

Output:

Subtraction of two matrices: 
2 5 3 
1 1 0 
0 1 2 

JAVA

Output:

Subtraction of two matrices: 
2 5 3 
1 1 0 
0 1 2 

C#

Output:

Subtraction of two matrices: 
2 5 3 
1 1 0 
0 1 2 

PHP

Output:

Subtraction of two matrices: 
2 5 3 
1 1 0 
0 1 2 

Next Topic#




Please Share

facebook twitter google plus pinterest

B.Tech / MCA


Learn Latest Tutorials