FOR FREE YEAR SOLVED

Matrix Subtraction

Back to Programming

Description

To perform the subtraction of the two matrices, first, the two matrices are taken as input. 

Let the two matrices be:

 

Now, for the subtraction of two matrices the number of rows and columns of the two matrices to be equal. Here both the matrices are a square matrix of order 3, so, subtraction is possible. The elements of the same index of two matrices are subtracted and the result is also stored in the same index of the resulting matrix.

The matrix subtraction will be performed as:

 

If the number of rows or the numbers of the columns of the two matrices are not equal then the subtraction will not be performed and an error message will be shown.

Algorithm

INPUT: Two Matrices
OUTPUT: Difference of two Matrices

PROCESS:
Step 1: [taking the inputs]
	Read m, n [the number of rows & columns of the 1st matrix]
	Read p, q [the number of rows & columns of the 2nd matrix]
Step 2: [subtraction of two matrices]
	If m=p and n=q then
		[take the elements of the matrix]
		For i=0 to m-1 repeat
			For j=0 to n-1 repeat
				Read a[i][j]
			[End of ‘for’ loop]
		[End of ‘for’ loop]
		For i=0 to p-1 repeat
			For j=0 to q-1 repeat
				Read b[i][j]
			[End of ‘for’ loop]
		[End of ‘for’ loop] 
		For i=0 to m-1 repeat
			For j=0 to n-1 repeat
				Set c[i][j]<-a[i][j]-b[i][j]
			[End of ‘for’ loop]
		[End of ‘for’ loop]
		[printing the difference of the matrix]
		Print “The difference of the two matrix: "
		For i=0 to m-1 repeat
			For j=0 to n-1 repeat
				Print c[i][j]
			[End of ‘for’ loop]
			Move to the next line
		[End of ‘for’ loop]
	else
		print "The subtraction is not possible"
	[End of ‘if’]
Step 3: Stop

Code

TIME COMPLEXITY: 

                                for(i=0;i<m;i++)--------------------------- O(m)

                                {        for(j=0;j<n;j++)--------------------- O(n)

                                                c[i][j]=a[i][j]-b[i][j];

                                }

The time complexity of the matrix subtraction is O(m*n). if it is a square matrix of order n, then the complexity will be O(n2).

 

APPLICATIONS:

  1. The matrix subtraction can be used as a translation or horizontal and vertical shift on the coordinate plane.

Related