In the programming sense, Matrices are Two Dimensional or 2D arrays. Just as Matrices have rows and columns, similarly 2D arrays too have rows and columns.
There are many mathematical operations like addition, subtraction, multiplication etc. which can be performed on matrices, and therefore to 2D arrays also. In this article, we will be discussing about the addition and subtraction of two 2D arrays (Matrices).
Addition of two Matrices (2D arrays)
For addition of two matrices both the matrices must have the same dimension. Ex. if matrice one has the dimension p x q then matrice two must have the dimension p x q.
In the addition process, each of the element of the first matrice is added to the corresponding element of the second matrice and result is stored in the third matrice having the same dimension (i.e. p x q). Below is the algorithm for adding two matrices.
Algorithm for adding two Matrices
Suppose,

Two 2D arrays to be mat1 [p][q] and mat2 [p][q] having p rows and q columns respectively.

A third 2D array, sum [p][q] to store the result.
Here is the algorithm:

FOR I = 0 TO (p1)

FOR J = 0 TO (q1)

sum [i][j] = mat1 [i][j] + mat2 [i][j]

END OF INNER LOOP

END OF OUTER LOOP
Subtraction of two Matrices
For subtraction, same rule applies. The process is also the same as for addition; we just need to use the subtraction operator instead of the addition operator ;)
Algorithm for subtracting two Matrices

FOR I = 0 TO (p1)

FOR J = 0 TO (q1)

sum [i][j] = mat1 [i][j]  mat2 [i][j]

END OF INNER LOOP

END OF OUTER LOOP
Here is the program that illustrates the implementation of both of these algorithms:
// Example program in C++ // It shows you how to add // and subtract two matrices #include<iostream.h> void main(void) { int i,j,ch; int mat1[3][3]; int mat2[3][3]; int sum[3][3]; cout<<"enter elements for mat1:"; for(i=0;i<=(31);i++) for(j=0;j<=(31);j++) cin>>mat1[i][j]; cout<<"enter elements for mat2:"; for(i=0;i<=(31);i++) for(j=0;j<=(31);j++) cin>>mat2[i][j]; cout<<"what do you want to do\n\n"; cout<<"1>addition\n2>subtraction\n"; cin>>ch; switch(ch) { case 1: // addition of matrices // is done here for(i=0;i<=(31);i++) for(j=0;j<=(31);j++) sum[i][j]=mat1[i][j]+mat2[i][j]; // till here break; case 2: // subtraction of matrices // is done here for(i=0;i<=(31);i++) for(j=0;j<=(31);j++) sum[i][j]=mat1[i][j]mat2[i][j]; // till her break; } // sum is shown for(i=0;i<=(31);i++) for(j=0;j<=(31);j++) cout<<"\n"<<sum[i][j]; cout<<endl; }
GoodBye for now!
Related Articles:
No comments:
Post a Comment
You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.
Please don't use abusive language.