Introduction – This tutorial first explains the concept of matrix addition. It then provides the Java code for adding 2 matrices of any size or dynamically sized matrices. The program prints an error if the two matrices being added are not of the same size.
How to add two matrices
Matrix addition formula says –
Given two matrices, M and N, of same size, the sum of these matrices is obtained by adding the numbers – M ricj + N ricj to get the number in ricj position of the resulting matrix.
Where, r is a row with 0 < i < rows-1
c is a column with 0 < j < columns-1 .
The above formula in matrix form looks like this –
Having understood how matrix addition is done, let us now see the java program for matrix addition, followed by the explanation of the code.
Java Program for matrix additionOUTPUT of the above code Explanation of the code
- The matrix addition logic is in the method named a
addMatrices()method takes two 2-dimensional
intarrays as input named
- It first checks if
m2are of same size i.e they have the same number of rows and columns.
- In case they are of different sizes then the method prints a message -“
Matrices not of same size. Cannot be added.” and returns the
m2are of same size, then the method created two nested for-loops which move through each and every position of the matrices. As the loop iterates, the elements at the same row and column position in both the matrices are added and put in a third 2-dimensional array named ‘
sumis our summed-up matrix which is returned at the end of the method.
- Note that
addMatrices()is totally dynamic as it does not take the size of the matrices as input anywhere. It reads the size of the matrices dynamically using
d2variables and then uses these variables for looping through the matrices. The method is thus fully dynamic.
printMatrix()method simply prints the input matrix in a pretty format with matrix elements arranged in rows and columns.
- In the
main()method two 2X2 matrices are initialized in variables
m2which are 2-dimensional
intarrays. These matrices are printed along with their calculated sum as shown in the output above.
- To check the algorithm for 2-dimensional matrices of any other sizes, you can initialize them in
main()and pass them to the
addMatrices()method to get their sum as return value.
In the above tutorial we first saw how matrix addition works and then saw the java program for implementing matrix addition along with detailed explanation of the code.