×

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are multiplied by the column element.

To perform multiplication in matrices, the column number of the first matrix is equal to the row number of the second matrix.

Example

  1. A [] [] = {{2,3}, {8,6}}
    B [] [] = {{6,0}, {0,3}}
    C [] [] = {{12,21}, {48,18}}

Explanation

In the above example, the order of both matrices is the same i.e., 2 X 2 and the column number is equal to the row number in the second matrix.

Example

  1. A [] [] = {{2,3}, {8,6}}
    B [] [] = {{6,0}, {0,3}, {5,7}}

Explanation

In the above example, the number of columns in the first matrix is not equal to the number of rows in the second matrix.

Approach for matrix multiplication 

  • Take two matrices
  • Check whether the matrices can be multiplied or not.
  • Construct a new matrix of order (row size of first column X column size of the second matrix)
  • Traverse through each element of the first matrix row-wise and multiply with the column element of second matrix and store the sum value in new matrix constructed.
  • Print the final matrix constructed.

Program for multiplication of two matrices using static method

MatrixMultiplication.java

import java.io.*;
import java.util.*;
class  MatrixMultiplication {
// Function to print Matrix
static void matrixPrint(int M[][],int rowSize,int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");
System.out.println();
}
}
// Multiplication of matrices A[][] and B[][] 
static void multiply(int row1, int col1, int A[][],int row2, int col2, int B[][])
{
int i, j, k;
// Print the matrices A and B
System.out.println("\nMatrix A:");
matrixPrint(A, row1, col1);
System.out.println("\nMatrix B:");
matrixPrint(B, row2, col2);
        // Check whether the multiplication is possible or not
if (row2 != col1) {
System.out.println("\nMultiplication of given matrices is not Possible");
return;
}
// Construct a new matrix with size of row1 x col2
int C[][] = new int[row1][col2];
// Multiply the two matrices
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < row2; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
// Printing the result
System.out.println("\nResultant Matrix:");
matrixPrint(C, row1, col2);
}
// Main Function
public static void main(String[] args)
{
        Scanner sc= new Scanner(System.in);
        int row1=4;
int  col1 = 3, row2 = 3, col2 = 4;
int A[][] = { { 3, 2, 2 },{ 8, 4,6 },{ 5, 4,9 },{ 2, 5,7} };
int B[][] = { { 3, 5, 2, 1 },{ 1, 3,9, 8 },{ 3, 5, 6,8 } };
multiply(row1, col1, A,row2, col2, B);
}
}

Output

Matrix Multiplication in Java

Program for multiplication of two matrices using dynamic method

MatrixMultiply.java

import java.io.*;
import java.util.*;
class  Main{
// Function to print Matrix
static void matrixPrint(int M[][],
int rowSize,
int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");
System.out.println();
}
}
// Multiplication of matrices A[][] and B[][] 
static void multiply(
int row1, int col1, int A[][],
int row2, int col2, int B[][])
{
int i, j, k;
// Print the matrices A and B
System.out.println("\nMatrix A:");
matrixPrint(A, row1, col1);
System.out.println("\nMatrix B:");
matrixPrint(B, row2, col2);
        
        // Check whether the multiplication is possible or not
if (row2 != col1) {
System.out.println("\nMultiplication of given matrices is not Possible");
return;
}


// Construct a new matrix with size of row1 x col2
int C[][] = new int[row1][col2];


// Multiply the two matrices
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < row2; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
// Printing the result
System.out.println("\nResultant Matrix:");
matrixPrint(C, row1, col2);
}


// Main Function
public static void main(String[] args)
{
        Scanner sc= new Scanner(System.in);
        int row1 = sc.nextInt();
int  col1 = sc.nextInt();
int row2 = sc.nextInt();
int col2 = sc.nextInt();


int A[][] = new int[row1][col1];
int B[][] = new int[row2][col2];
        for(int i=0;i<row1;i++)
        {
            for(int j=0;j<col1;j++)
            {
                A[i][j]=sc.nextInt();
            }
        }
        for(int i=0;i<row1;i++)
        {
            for(int j=0;j<col1;j++)
            {
                B[i][j]=sc.nextInt();
            }
        }
multiply(row1, col1, A,
row2, col2, B);
}
}

Output:

Matrix Multiplication in Java

Related Topics

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.