We can add two matrices in java using binary * operator and multi-dimensional arrays creation. In java “array of arrays “ approach is used for create multi-dimensional array.
In case of matrix multiplication, one row element of first matrix is multiplied by all the columns of the second matrix.
Example :
We have two matrices A and B of same size and we have to multiply them..
Input: A[][] = {{2, 3}, {5, 4}} B[][] = {{5, 2}, {3, 4}} Output: {{19, 16}, {37, 26}}
Example – Program to Multiply two matrices
public class MatricesMultiply { public static void main(String args[]) { int a[][] = { { 2, 3 }, { 5, 4 } }; int b[][] = { { 5, 2 }, { 3, 4 } }; int c[][] = new int[2][2]; // 2 rows and 2 columns for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { c[i][j] = 0; for (int k = 0; k < 2; k++) { c[i][j] += a[i][k] * b[k][j]; } System.out.print(c[i][j] + " "); // printing matrix element } System.out.println(); } } }
Output
19 16 37 26
Example – Using independent method
public class MatricesMultiply { public static void main(String[] args) { int a[][] = { { 2, 3 }, { 5, 4 } }; int b[][] = { { 5, 2 }, { 3, 4 } }; int[][] sum = multiplyMatrices(a, b); System.out.println("The Multiplication of two matrices is: "); printMatrix(sum); } public static int[][] multiplyMatrices(int[][] a, int[][] b) { int c[][] = new int[2][2]; // 2 rows and 2 columns for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { c[i][j] = 0; for (int k = 0; k < 2; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return c; } public static void printMatrix(int[][] matrix) { int rows = matrix.length; int columns = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
Output
The Multiplication of two matrices is: 19 16 37 26