×

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

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute 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 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.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 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.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.