×

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

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.