FOR FREE MATERIALS

Matrix Addition

Back to Programming

Description

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

Let the two matrices be:

 

Now, for the addition 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, the addition is possible. The elements of the same index of two matrices are added and the result is also stored in the same index of the resulting matrix.

The matrix addition will be performed as:

 

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

Algorithm

INPUT: Two Matrices
OUTPUT: Sum 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: [addition 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 sum of the matrix]
		Print “The sum 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 addition 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 is O(m*n). if it is a square matrix of order n, then the complexity will be O(n2).

 

APPLICATIONS:

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

Contributed by