Wednesday, April 24, 2024
HomeJavaJava Program to Multiply Two Matrices

Java Program to Multiply Two Matrices


The best way to write a Java program to multiply two matrices in Java is an excellent programming train to get aware of the two-dimensional array in Java. this instance teaches about the way to multiply arrays, the way to entry components from a multi-dimensional array, the way to move them to a perform and so forth. For the reason that matrix is a pure illustration of a multi-dimensional array in Java, they’re usually used as an instance actual phrase matrix workout routines e.g. the calculating sum of two matrices or calculating the distinction of two matrices, and so forth. It is also one of many common Matrix based mostly coding issues you could find on coding interviews. 
By the way in which, earlier than writing this system, let’s recap the way to multiply two matrices in arithmetic first. When you bear in mind, you possibly can solely multiply two matrices if, and provided that, the variety of columns within the first matrix equals the variety of rows within the second matrix. That is named the matrix multiplication criterion.

If each matrices do not fulfill that criterion then the product of two matrices is undefined. The Product matrix’s dimensions will likely be equal to (rows of the primary matrix) × (columns of the second matrix ). For instance, if we multiply a 2×3 matrix with a 3×1 matrix, then the product matrix or consequence matrix will likely be a 2×1 matrix i.e. two rows and 1 column.

I used to recollect this trick by writing dimensions of matrices adjoining to one another and canceling their matching dimension e.g. should you write 2x3 and 3x1, after which cancel 3 from either side you’ll get a matrix of dimension 2×1, which is principally the dimension of the product matrix.

The best way to multiply two matrices in Java? Instance 

Here’s a graphical illustration of the matrix multiplication algorithm:

Java Program to Multiply Two Matrices - Matrix Multiplication Example

You possibly can see that each matrices met the situation for multiplication i.e. columns of the primary matrix are equal to rows of the second matrix. Then we multiply the primary row of the primary matrix to the primary column of the second matrix and this offers us the primary component of the primary column of consequence matrix.

Equally, while you multiply the second row of the primary matrix to the primary column of the second matrix you get the second component of the primary column within the consequence matrix.

The best way to multiply two matrices in Java- Instance

Right here is our full Java program to carry out matrix multiplication. On this program, we first ask the person to enter two matrices. Since you can’t settle for an array from the command line in Java (see right here), we ask the person to first enter the variety of rows and columns of the matrix after which ask him to populate the matrix.

As soon as we’ve got each the matrices prepared we first examine whether or not they met the situation of matrix multiplication or not i.e. variety of columns of the primary matrix matches to the rows of the second matrix. As I mentioned, we’ve got used a two-dimensional array to signify a matrix in Java.

import java.util.Scanner;

/**
* Java program to calculate product of Two matrices in Java. As a way to
* multiply two matrices, column of first matrix should be equal to rows
*  of the second
* matrix.
*
* @creator Javin Paul
*/
public class MatrixMultiplication{

    public static void essential(String args[]) {

        Scanner cmd = new Scanner(System.in);
        System.out.println("Enter the variety of rows and columns of 
                             first matrix");

        int rowsOfFirstMatrix = cmd.nextInt();
        int columnsOfFirstMatrix = cmd.nextInt();
        int[][] aMatrix = new int[rowsOfFirstMatrix][columnsOfFirstMatrix];

        System.out.println("Enter the weather of first matrix");
        for (int i = 0; i < rowsOfFirstMatrix; i++) {
            for (int j = 0; j < columnsOfFirstMatrix; j++) {
                aMatrix[i][j] = cmd.nextInt();
            }
        }

        System.out.println("Enter the variety of rows and columns of the
                                second matrix");
        int rowsOfSecondMatrix = cmd.nextInt();
        int columnsOfSecondMatrix = cmd.nextInt();

        // security web - examine order or every matrix, whether or not eligible for
        // multiplication or not
        whereas (columnsOfFirstMatrix != rowsOfSecondMatrix) {
            System.out.printf("Matrices with entered orders cannot be
                         multiplied with one another, " 
                  + "columnsOfFirstMatrix [%d] != rowsOfSecondMatrix [%d] %n",
                    columnsOfFirstMatrix, rowsOfSecondMatrix);
            System.out.println("Enter the variety of rows and columns of 
                                   second matrix");
            rowsOfSecondMatrix = cmd.nextInt();
            columnsOfSecondMatrix = cmd.nextInt();
        }

        int[][] bMatrix = new int[rowsOfSecondMatrix][columnsOfSecondMatrix];
        System.out.println("Enter numbers of second matrix");
        for (int i = 0; i < rowsOfSecondMatrix; i++) {
            for (int j = 0; j < columnsOfSecondMatrix; j++) {
                bMatrix[i][j] = cmd.nextInt();
            }
        }

        // calculating product of two matrices in Java
        int[][] product = product(aMatrix, bMatrix);
        System.out.println("Product of entered matrices:-");

        for (int i = 0; i < rowsOfFirstMatrix; i++) {
            for (int j = 0; j < columnsOfSecondMatrix; j++) {
                System.out.printf("%d ", product[i][j]);
            }
            System.out.printf("%n");
        }
        cmd.shut();
    }

    /**
     * Technique to calculate multiplication or product of two matrices.
     *
     * @param matrix1
     * @param matrix2
     * @return product of two matrix
     */
    public static int[][] product(int[][] matrix1, int[][] matrix2) {
        int columnsOfFirstMatrix = matrix1[0].size;
        int rowsOfSecondMatrix = matrix2.size;

        if (columnsOfFirstMatrix != rowsOfSecondMatrix) {
            throw new IllegalArgumentException(String.format("Cannot multiply
                      matrices, columns of first matrix"
                    + " %d is just not equal to rows of second matrix %d", 
                      columnsOfFirstMatrix, rowsOfSecondMatrix));
        }

        int rowsOfFirstMatrix = matrix1.size;
        int columnsofSecondMatrix = matrix2[0].size;
        int[][] product = new int[rowsOfFirstMatrix][columnsofSecondMatrix];

        for (int i = 0; i < rowsOfFirstMatrix; i++) {
            for (int j = 0; j < columnsofSecondMatrix; j++) {

                int sum = 0;
                for (int okay = 0; okay < rowsOfSecondMatrix; okay++) {
                    sum = sum + matrix1[i][k] * matrix2[k][j];
                }

                product[i][j] = sum;
            }
        }

        return product;
    }

}

and right here is the output of this program when you’ll run this in your favourite Java IDE e.g. Eclipse or IntelliJIDEA or simply from the command immediate:

Output:
Enter the quantity of rows and columns of the first matrix
2 3
Enter the components of the first matrix
1 2 3
4 5 6
Enter the quantity of rows and columns of the second matrix
2 4
Matrices with entered orders cannot be multiplied with one another, 
columnsOfFirstMatrix [3] != rowsOfSecondMatrix [2]
Enter the quantity of rows and columns of the second matrix
3 2
Enter numbers of the second matrix
7 8
9 10
11 12
The product of entered matrices:-
58 64
139 154

You possibly can see that our first instance was not excellent, the matrices we entered can’t be multiplied with one another as a result of columns of the primary matrix usually are not equal to rows of the second matrix.

That is all about the way to do matrix multiplication in Java. This can be a good programming train to study and perceive the way to use two-dimensional arrays in Java, which is among the key knowledge constructions, particularly for the sport improvement area. 

If you’re simply beginning with programming and never aware of key programming ideas then I additionally recommend you be a part of these interactive programming programs which train you the fundamentals of programming in Java and different programming languages.

Different Java Programming workout routines for rookies

  • The best way to transpose Matrix in Java? (program)
  • The best way to depend vowels and consonants in given String in Java? (resolution)
  • The best way to examine if two rectangles intersect with one another in Java? (resolution)
  • The best way to implement Linear Search in Java? (resolution)
  • The best way to print Fibonacci sequence in Java (resolution)
  • The best way to examine if two given Strings are Anagram in Java? (resolution)
  • The best way to calculate the sq. root of a given quantity in Java? (resolution)
  • The best way to calculate the sum of all components of an array in Java? (program)
  • The best way to implement binary search utilizing recursion in Java? (resolution)
  • The best way to examine if given String is palindrome or not in Java? (resolution)
  • The best way to take away duplicate characters from String in Java? (resolution)
  • The best way to examine if a yr is a intercalary year in Java? (resolution)
  • The best way to reverse phrases in a given String in Java? (resolution)
  • The best way to examine if given quantity is prime in Java (resolution)
  • The best way to calculate Space of Triangle in Java? (program)
  • The best way to discover if given Integer is Palindrome in Java? (resolution)
  • The best way to discover all permutations of a given String in Java? (resolution)
  • The best way to examine if a String accommodates duplicate characters in Java? (resolution)
  • The best way to reverse an array in place in Java? (resolution)
  • The best way to reverse a String in place in Java? (resolution)
  • The best way to take away duplicate components from the array in Java? (resolution)
  • The best way to discover the very best occurring phrase from a given file in Java? (resolution)
  • The best way to calculate the typical of all numbers of an array in Java? (program)

Thanks so much for studying this text thus far. When you discover the answer of Matrix multiplication in Java and perceive idea higher then please share this Java tutorial with your mates and colleagues. If in case you have any questions be at liberty to ask in feedback. 

P. S. – If you’re new to Java and on the lookout for free on-line programs and tutorials to study Java then you can even checkout this listing of 5 finest Free Core Java Programs for Newcomers. This listing accommodates finest free programs to study Java on-line from Udemy and Coursera.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments