Multiplying Matrices in Java: A Step-by-Step Guide

Multiplying Matrices in Java: A Step-by-Step Guide

Multiplying matrices in Javais a fundamental operation in linear algebra, and it finds applications in various fields like computer graphics, data analysis, and scientific computing. In this article, we’ll explore how to multiply matrix Java. We will break down the process into easy-to-follow steps, provide Java code snippets, and explain each step in detail. 

But, for now, let us dive into today’s topic without waiting any further!

TL;DR: Multiplying Matrices In Java 

Aspect

Summary

Matrix Basics

Matrices are 2D arrays in Java, which are used for operations like addition, subtraction, and multiplication.

Multiplication Rules

Two matrices can be multiplied only if the columns of Matrix A are equal to the rows of Matrix B. The Result matrix dimension will be rows(A) x columns(B).

Dot Product Logic

We have to multiply the row elements of A by the column elements of B. Then, we have to sum them and place the result in the output matrix.

Java Implementation

We will use nested loops to read matrices, and then validate the multiplication condition. At last, we will perform the dot-product operation.

Steps Of Implementation

  • Take the Input dimensions.
  • Validate the input values.
  • Implement a triple-nested loop for multiplication.
  • Print the result matrix.

Introduction To Matrices & Matrix Multiplication

Matrices are the mathematical structures that store numbers as a rectangular array. Just like a table, they have rows and columns. They are used not only in mathematics but also in physics and computer science for different purposes.

introduction_to_matrices

Since they deal with numbers, we can perform various operations on them as well. Some of these operations are:

  • Matrix addition
  • Matrix subtraction
  • Matrix multiplication
  • Complement of a matrix

In this article, we will learn about multiplying matrices. Once we learn the steps for multiplication, we will also perform this using the Java programming language. The following sections of this article will clear up all your doubts, so keep reading!

Just like the simple multiplication process, in matrix multiplication, two different matrices are multiplied to produce a new matrix. This multiplication is often called the dot product of the two matrices. 

However, not all matrices can be multiplied. To multiply two matrices, you need to make sure the matrices fulfill the following conditions. Read below to know what these are.

To multiply 2 matrices: 

  • The number of columns in the first matrix must be equal to the number of rows in the second matrix.
  • The dimensions of the product matrix should be equal to the number of rows in the first matrix and the number of columns in the second matrix. 

This means – 

Matrix 1 [ m1 x n1 ] * Matrx 2 [m2 x n2]  = Matrix 3 [ m1 x n2 ]

where n1 = m2 

Understanding Matrix Multiplication: Rules And Formula

As we discussed above, while multiplying matrices, we need to keep two things in mind: the dimensions of the product matrix and the criteria for matrix multiplication. Let us understand these with the help of an example. 

Let us consider two matrices:

  • Matrix A has the dimensions: 2 x 3
  • Matrix B has the dimensions: 3 x 4

Can we multiply these matrices? The answer is yes! This is because the number of columns of the first matrix is equal to the number of rows of the second matrix. 

Now, what do you think should be the dimension of the product matrix, say Matrix C? Well, if you answered 2 x 4, you are right! 

However, if Matrix A had dimensions 2 x 3 and Matrix B had dimensions 2 x 2, multiplying both these matrices wouldn’t be possible in this case. Let us understand the logic behind it. 

Mathematical Logic Behind Matrix Multiplication

Remember, we told you that matrix multiplication is the dot product of the two matrices? Well, the same logic is used in this case. The image given below will help you understand the steps for calculating the product of two matrices. 

rule_to_multiplySteps for calculating the dot product for matrix multiplication

  1. Go row-by-column, which means multiply each element of each row of matrix A with each element of each column of matrix B. 
  2. Multiply the corresponding elements and add them.
  3. Put the result in the correct cell. Refer to the image given below to see the placement of the elements in the resulting matrix.

example_multiplication

In Java, we perform this multiplication with the help of nested loops. In the section below, we will implement a program for multiplying matrices in Java. Keep reading to learn more!

Step-by-Step Matrix Multiplication In Java (With Code Example)

Now that we have understood the basic rules and process for multiplying matrices, let us try to implement this with the help of a Java program. In this example, we will ask the user to provide us with the information about the matrices that we need to multiply. 

Code Example:

				
					import java.util.Scanner;


public class MatrixMultiplication{
    public static void main(String[] args) {
        // Create a scanner object to get user inputs
        Scanner scanner = new Scanner(System.in);


        // Input dimensions for Matrix A
        System.out.println("Enter the details for Matrix A\n");
        // Get the number of rows and columns for Matrix A
        System.out.println("Enter number of rows for Matrix A:");
        int rowsA = scanner.nextInt();
        System.out.println("Enter number of columns for Matrix A:");
        int colsA = scanner.nextInt();


        // Input dimensions for Matrix B
        System.out.println("Enter the details for Matrix B\n");
        // Get the number of rows and columns for Matrix B
        System.out.println("Enter number of rows for Matrix B:");
        int rowsB = scanner.nextInt();
        System.out.println("Enter number of columns for Matrix B:");
        int colsB = scanner.nextInt();


        // Check if matrices can be multiplied
        if (colsA != rowsB) {
            System.out.println("Matrix multiplication not possible. Number of columns of Matrix A must equal to the number of rows of Matrix B.");
            return;
        }


        // Input values for Matrix A
        int[][] matrixA = new int[rowsA][colsA];
        System.out.println("Enter elements of Matrix A:");
        // Use the nested for loop to get the elements for the 2D matrix
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsA; j++) {
                matrixA[i][j] = scanner.nextInt();
            }
        }


        // Input values for Matrix B
        int[][] matrixB = new int[rowsB][colsB];
        System.out.println("Enter elements of Matrix B:");
        // Use the nested for loop to get the elements for the 2D matrix
        for (int i = 0; i < rowsB; i++) {
            for (int j = 0; j < colsB; j++) {
                matrixB[i][j] = scanner.nextInt();
            }
        }


        // Multiplying matrices using the dot product approach
        int[][] result = new int[rowsA][colsB];
        // Using for loop nesting for multiplying Matrix A with Matrix B
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                for (int k = 0; k < colsA; k++) {
                    result[i][j] += matrixA[i][k] * matrixB[k][j];
                }
            }
        }


        // Print the product Matrix
        System.out.println("Product Matrix:");
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                System.out.print(result[i][j] + "\t");
            }
            System.out.println();
        }


        // Close the scanner object to prevent memory leaks
        scanner.close();


    }
}

				
			

Explanation Of The Code:

  • In the above code, we are first taking the input dimensions of Matrix A and Matrix B from the user.
  • After we have the dimensions, we are checking whether the matrices satisfy the condition for multiplication. This step is important to prevent any errors.
  • Once validated, we can start getting the elements of the matrices using the nested for loop. These loops help to store the values in a 2D array.
  • Next, using the formula result[i][j] += matrixA[i][k] * matrixB[k][j]; we are calculating the dot product.
  • The variable ‘k’ is the common dimension.
  • After the calculation, the product matrix is printed.

Now, let’s put all the code together and run the program to see the output. Java coding often requires practice, especially when working with mathematical operations like matrix multiplication. There are many Java coding platforms where you can enhance your coding skills.

Output:

With Product Matrix

output_with_product

Without Product Matrix

output_without_product

“Matrix multiplication often appears in programming assignments. If you’re struggling with similar problems, our Java Project Help service can guide you step-by-step.”

matrix multiplication flowchart

Java Program To Multiply Two Matrices

Now, let’s create a Java Program To Multiply Two Matrices step by step.

  • Step 1: Define Matrices A and B

First, we need to define the two matrices, A and B, that we want to multiply. We’ll use two-dimensional arrays to represent these matrices.

				
					
public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] matrixA = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrixB = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    }
}

				
			

In this example, we’ve defined two 3×3 matrices, matrixA and matrixB. You can replace these values with your own matrices of the desired size.

  • Step 2: Create a Result Matrix

Next, we’ll create an empty matrix, C, to store the result of the multiplication. The size of matrix C will be determined by the number of rows in matrix A and the number of columns in matrix B.

				
					
int rowsA = matrixA.length;
int colsA = matrixA[0].length;
int colsB = matrixB[0].length;

int[][] resultMatrix = new int[rowsA][colsB];

				
			
  • Step 3: Perform Matrix Multiplication

Now, we’ll implement the matrix multiplication algorithm. We’ll use nested loops to iterate through the rows and columns of matrices A and B and compute the elements of matrix C.

				
					
for (int i = 0; i < rowsA; i++) {
    for (int j = 0; j < colsB; j++) {
        for (int k = 0; k < colsA; k++) {
            resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
        }
    }
}



				
			

In the innermost loop, we calculate the sum of products for each element of matrix C.

  • Step 4: Display the Result

Finally, let’s display the result matrix, C.

				
					
System.out.println("Result Matrix (C):");
for (int i = 0; i < rowsA; i++) {
    for (int j = 0; j < colsB; j++) {
        System.out.print(resultMatrix[i][j] + " ");
    }
    System.out.println(); // Move to the next row
}

				
			

Now, let’s put all the code together and run the program to see the output. Java coding often requires practice, especially when working with mathematical operations like matrix multiplication. If you want to practice more Java coding challenges, check out our curated list of Java coding problems to enhance your skills.

 Code To Multiply Two Matrices:

				
					
public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] matrixA = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrixB = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
        
        int rowsA = matrixA.length;
        int colsA = matrixA[0].length;
        int colsB = matrixB[0].length;
        
        int[][] resultMatrix = new int[rowsA][colsB];
        
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                for (int k = 0; k < colsA; k++) {
                    resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
                }
            }
        }
        
        System.out.println("Result Matrix (C):");
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                System.out.print(resultMatrix[i][j] + " ");
            }
            System.out.println(); // Move to the next row
        }
    }
}



				
			

Output:

Output- Java Program To Multiply Two Matrices

The output represents the result matrix C obtained by multiplying two input matrices, A and B, using the Java program.

Each number in the output matrix corresponds to a specific element obtained by applying the matrix multiplication formula.

The resulting matrix C contains the linear combinations of elements from matrices A and B, reflecting the product of these matrices. In this specific example, the resulting matrix C is a 3×3 matrix with each element calculated through the matrix multiplication process, as explained earlier.

Comparison Table Between Strassen Vs. Naive Matrix Multiplication Java:

Along with the Native Matrix Multiplication approach, another advanced approach, known as the Strassen Approach, has a much lower Time Complexity.

Here, we have developed a comparison table between the Strassen and Native Multiplication approaches.

Criteria

Native Matrix Multiplication

Strassen Matrix Multiplication

Implementation

Simple

Complex

Speed

Slow

Faster

Memory Usage

Low

High

Stability

Stable

Unstable

Code Length

Short

Long



Common Mistakes To Avoid While Multiplying Matrices In Java

Let us now look at some common mistakes that beginners make while multiplying matrices in Java. We will also see what steps or approaches we can use to avoid them in your code. Read the points below to learn more about them.

common_mistakes_to_avoid

  • Incorrect Matrix Size Assumptions: Many times, programmers take user input and directly apply the formula to multiply matrices. Since this causes errors in the program, we should always validate the dimensions of the matrices that are to be multiplied. 

Always remember the multiplication rule: the number of columns of the first matrix must be the same as the number of rows of the second one. This will help you avoid miscalculations.

  • Misplaced Loop Indices: Another mistake that beginners make is when writing the instructions in the nested loop. Notice how we have a new variable ‘k’ in the loop. 

This variable is used to traverse the common dimensions of the two matrices. Follow the correct formula and write the loop in a structured way to avoid this confusion. 

  • Overwriting Output Matrix: Sometimes developers forget to initialise the values of the product matrix before starting their calculations. This leads to incorrect results and can become a problem. Also, many times, one value is overwritten for one cell.

Try to implement proper nesting and make sure to initialise the starting values to zero. This will give you accurate results. 

How To Do Concurrent Matrix Multiplication In Java?

In modern-day computers, there are multiple CPU Cores. We can perform Concurrent Matrix Multiplication using Multithreading, which will speed up the multiplication process by breaking it into smaller tasks.

These smaller tasks run in parallel and utilize full CPU power. Let us check the following code to know more.

				
					
import java.util.concurrent.*;


// Extending The RecursiveAction To Use Fork Framework
public class Main extends RecursiveAction 
{
    private static final int THRESHOLD = 1; // The Threshold Value
    private int[][] A, B, C; // The Matrices


    private int row;


    // Constructor For Initializing The Data
    public Main(int[][] A, int[][] B, int[][] C, int row) 
    {
        this.A = A;
        this.B = B;
        this.C = C;
        this.row = row;
    }


    @Override
    protected void compute() 
    {
        if (row >= A.length) 
            return;


        // Multiplication Process
        for (int j = 0; j < B[0].length; j++)
            for (int k = 0; k < A[0].length; k++)
                C[row][j] += A[row][k] * B[k][j];


        // Creating The Next Task To Process
        invokeAll(new Main(A, B, C, row + 1));
    }


    public static void main(String[] args) 
    {
        int[][] A = {{10, 21}, {30, 43}};
        int[][] B = {{50, 65}, {70, 87}};
        int[][] C = new int[2][2];


        // Creating a ForkJoinPool To Execute The Tasks
        ForkJoinPool pool = new ForkJoinPool();


        // The Execution Will Start
        pool.invoke(new Main(A, B, C, 0));


        System.out.println("Concurrent Matrix Multiplication: ");
        // Printing The Result
        for (int[] row : C)
            for (int num : row) 
                System.out.print(num + " ");
            
        System.out.println(); // Move to next line after output
    }
}


				
			

Explanation Of The Code: 

  • At first, the Main Function will be extended to the recursive action for the Fork Framework.
  • Now, we will create the Constructor to initialize the data in the program.
  • Later, the Override Annotation will be used, and the matrix multiplication will be done.
  • Then, we will invoke all the tasks and create the next task.
  • At last, the input matrices will be provided, and ForkJoinPool() and Invoke() will be called to start execution.

Output: 

Concurrent Matrix Multiplication Output

How To Transpose And Multiply A Matrix In Java?

Sometimes, beyond two matrix multiplications, you have to perform multiplication between a matrix and its transpose. This is a very common practice in Machine Learning, Statistics, and other calculations.

Let us check the following code, where we will transpose a matrix first and then perform multiplication.

This version is also known as the Bottom-Up Sort. Let us check the following code for full implementation.

				
					
public class Main 
{
    public static int[][] trans(int[][] M) // Function To Transpose
    {
        int rows = M.length; // Getting The Row Length
        int cols = M[0].length; // Getting The Column Length
        int[][] T = new int[cols][rows];


        // Calculating The Transpose
        for (int i = 0; i < rows; i++) 
            for (int j = 0; j < cols; j++)
                T[j][i] = M[i][j];
                
        return T;
    }


    public static int[][] multiply(int[][] A, int[][] B) // Function To Multiply
    {
        int[][] C = new int[A.length][B[0].length];


        // Implementing Multiply Logic
        for (int i = 0; i < A.length; i++)
            for (int j = 0; j < B[0].length; j++)
                for (int k = 0; k < A[0].length; k++)
                    C[i][j] += A[i][k] * B[k][j];
        return C;
    }


    public static void main(String[] args) 
    {
        int[][] A = {{12, 21}, {34, 40}};
        int[][] T = trans(A);
        int[][] result = multiply(A, T);


        System.out.println("Transpose And Multiply Matrix: ");
        for (int[] row : result)
            for (int num : row) 
                System.out.print(num + " ");
        
        System.out.println();
    }
}


				
			

Explanation Of The Code:

  • At first, a matrix will be taken as the input and will be shared with the Trans() function for transpose.
  • Now, we will just swap the Rows with the Columns in that function and get the Transpose Matrix.
  • Then, the Multiply() function will be called, where these two functions will be multiplied using the previous logic.
  • In the end, we will print the multiplication result on the screen.

Output: 

Transpose And Multiply Matrix Output

The Use Of Matrix Multiplication In Real World Applications

As we said before, matrix multiplication is not only used for mathematical calculations, but also in Computer Science. Modern computing requires matrices and their applications across different industries. 

Let us see some of the use cases of these matrices and matrix multiplication below – 

  • Game Development and Graphics: The 3D characters or objects that you see on your screen are defined using vertices, and these vertices can be manipulated with the help of transformations of matrices. 

Concepts like Rotation, Scaling, and Translation utilise matrices. By multiplying the different matrices with the vertices of the desired object, we can change the appearance of the objects or define how characters move from one position to another.

  • Artificial Intelligence & Machine Learning: Artificial Intelligence and its subsets, like Machine Learning and Deep Learning, make use of matrix multiplication for developing different kinds of algorithms. 

Techniques like Neural Networks, Forward Propagation, Training, and Back Propagation use matrix multiplication for adjusting weights on nodes during their processing.

  • Image Processing: Matrices are also used in manipulating different images. This is extremely useful in the case of Computer Vision. Here, we apply another matrix, commonly called a kernel or filter, to an existing image matrix. This process is known as convolution. 

Some processes that you can use with image processing are- blurring effect, sharpening, edge detection, etc. With matrix multiplication, you can turn raw images into meaningful visualizations.

Conclusion:

I hope that you now know about multiplying matrices in Java. On first glance, we feel that a simple mathematical calculation may not be useful here. However, matrices are used across many tech industries as discussed above.

It is also important to note and be mindful of using nested loops to prevent infinite looping or inefficient memory storage.

Takeaways:

  • The resultant matrix after multiplication of the two matrices is their dot product.
  • Always make sure to validate whether the matrices can be multiplied or not to prevent runtime errors.
  • Keep in mind the common mistakes and ways to avoid them to write better Java code for matrix multiplication.