×

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java

The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will learn how to multiply matrices.

To find the multiplication of two matrices, we take elements of the first matrix row-wise and elements of the second matrix column-wise. The steps involved to find the multiplication of matrices is given below.

Step 1: Take two input matrices. Let’s assume the input matrices are:

Matrix Multiplication Program in Java

Here, Ma is the first input matrix, and Mb is the second input matrix.

Step 2: Compare the number of columns of the first matrix with the number of rows of the second matrix. It must be equal otherwise multiplication is not possible.

In our case, the number of columns in matrix Ma is 3, and the number of rows in matrix Mb is 3.

Step 3: Now, take elements of the first matrix row-wise and elements of the second matrix column-wise and do the multiplication and then perform the addition to get the element of the resultant matrix. Thus, elements of the first row of matrix Ma get multiplied to elements of the first column of matrix Mb, and elements of the second row get multiplied to the elements of the second column, and so on. Mathematically it can be represented as:

Matrix Multiplication Program in Java

Let’s implement the logic in a Java program.

Filename: MatrixMultiplication.java

 public class MatrixMultiplication
{
public static void main(String argvs[])
{
               // first input matrix
               int[][] arr1 = { { 12, 3, 4 }, { 51, 23, 31 }, { 5, 6, 7 } };
               // second input matrix
               int[][] arr2 = { { 0, 50 }, { 45, 46 }, { 1, 9 } };
               // calculating number of columns of the first matrix
               int colOfArr1 = arr1[0].length;
               // calculating number of rows of the first matrix
               int rowOfArr1 = arr1.length;
               // calculating number of rows of the second matrix
               int rowOfArr2 = arr2.length;
               // calculating number of columns of the second matrix
               int colOfArr2 = arr2[0].length;
               if(colOfArr1 != rowOfArr2)
               {
                               System.out.print("Multiplication of the given matricx is not possible");
               }
                // reaching here means the number of columns of the first matrix
                // is equal to the number of rows of the second matrix.
                // Hence, multiplication of the given matrices are possible
               else 
               {
                     // contains the output matrix
                      int[][] result = new int[rowOfArr1][colOfArr2];
                     // performing multiplication of the input matrices
                     for (int i = 0; i < rowOfArr1; i++) // loop for the rows of the output matrix
                     {
                               // loop for the columns of the output matrix
                               for (int j = 0; j < colOfArr2; j++)
                               {
                                              // for storing output of every element of the output matrix
                                              int sum = 0;
                                              for (int k = 0; k < colOfArr1; k++)
                                              {
                                                             // taking elements row-wise for the first input matrix
                                                              //and column-wise for the second
                                                             // input matrix
                                                              sum = sum + ( arr1[i][k] * arr2[k][j] );           
                                              }
                                              // updating our result matrix
                                              result[i][j] = sum;
                               }
                     }
                     // Displaying the outcome
                    System.out.println("Multiplication of the given two matrices is: ");
                     for(int row = 0; row < rowOfArr1; row++)
                     {
                                              for (int col = 0; col < colOfArr2; col++)
                                              {
                                                             System.out.print(result[row][col] + " ");
                                              }
                                              System.out.println("");
                     }
               }    
}
} 

Output:

 Multiplication of the given two matrices is:
139 774
1066 3887
277 589 

Explanation: We are nesting Java for-loop to the third degree to achieve our result. The innermost loop handles the multiplication process by taking elements row-wise for the first input array and column-wise for the second input array. We observe that in the given matrix the number of columns of the first matrix is equal to the number of rows of the second matrix.

The multiplication of two matrices is also a matrix whose row size is equal to the row size of the first matrix, and the column size is the same as the column size of the second matrix.

Mathematically, if Ma is an r1 * r2 matrix, and Mb is an r2 * c2 matrix. Then, Ma * Mb = r1 * c2 matrix. Here, r1 and r2 are the row size and column size of the matrix Ma, whereas r2 and c2 are the row size and column size of the matrix Mb.


Related Topics

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.