Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Matrix Program in Java

Last Updated on June 6, 2023 by Mayank Dham

Matrices are fundamental mathematical structures used in various computational tasks, and their implementation in Java provides a powerful tool for solving complex problems. A matrix is a two-dimensional array that can store elements of different data types, such as numbers, characters, strings, symbols, or expressions. In this article, we will explore the concept of matrices in Java, covering topics such as accessing matrix elements, creating matrix programs, and performing common matrix operations like addition, subtraction, and multiplication. By understanding matrix in Java, programmers gain the ability to handle multidimensional data, solve mathematical equations, manipulate data sets, and perform transformations, opening up a wide range of possibilities for applications in areas like data science, image processing, and scientific computing.

What is a Matrix?

In simple words, the matrix is a two-dimensional (2-D) array. The rectangular-shaped matrix can contain any data type like numbers, characters, strings, symbols, or expressions.

In the above, we have taken one matrix for example. The size of the matrix is n*m where n is the number of rows and m is the number of columns. Let’s see how we can access an element from the matrix.

From the above picture, if we want to access the first element of the first row we can use a [0][0] where a is the name of an array. Now, if we want to access the element from any row or column we can use a[i][j] where i is the row number and j is the column number. Let’s try to write a simple matrix program in java.

Simple Matrix Program in Java:

Now, we will try to create a simple matrix program in java. In which we will print the matrix and access the matrix element.

// matrix program in java
class HelloWorld {
    public static void main(String[] args) {
        
        // 2D natrix
        int a[][]={
                    {5,6,2},
                    {9,7,1},
                    {8,3,1}
                    };
        // the size of the matrix
        // n = total numbers of rows
        // m = total numbers of columns
        int n=a.length;
        int m=a[0].length;
        
        // print the matrix
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                System.out.print(a[i][j]+" ");
            }
            System.out.println();
        }
        
        System.out.println("Element at i=2 and j=1 position: "+a[2][1]);
    }
}

Output:

5 6 2 
9 7 1 
8 3 1 
Element at i=2 and j=1 position: 3

In the above program, first, we created a 3*3 size matrix with random integers. After that, we find the size of a matrix using the length method. Now, we will print the matrix using two loops. The outer loop is to iterate through rows. The inner loop is to iterate through the columns.

Addition Matrix Program in Java:

The addition of the two matrices is possible only when both matrices have the same size. For example, if matrix A is having size 45 and matrix B is having size 45 then only the addition is possible. Now, if matrix A is having size 45 and matrix B is having size 54 then the addition is not possible.

In the above example, we have taken two matrices with random integer values. In the image, we can see that the addition is performed on each element with its corresponding element of another matrix. In the result, we can see that elements of both the matrix summed up with their respective position in the matrix. Let’s see how to write an addition matrix program in java.

// addition matrix program in java
class HelloWorld {
    public static void main(String[] args) {
        
        // 2D natrix
        int a[][]={
                    {5,6,2},
                    {9,7,1},
                    {8,3,1}
                    };
        int b[][]={
                    {2,4,1},
                    {7,6,4},
                    {9,2,5}
                    };
                    
        int n=a.length;
        int m=a[0].length;
        
        // matrix to store the result
        int result[][]=new int[n][m];
        
        // addition of the matrices
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                result[i][j]=a[i][j]+b[i][j];
            }
        }
        
        System.out.println("Matrix after addition: ");
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                System.out.print(result[i][j]+" ");
            }
            System.out.println();
        }
    }
}

Output:

Matrix after addition: 
7 10 3 
16 13 5 
17 5 6 

In the above program, we created two matrices of the same size with random integers. After that, we have taken a matrix result to store the answer. We used two loops to perform the addition of the matrices and stored the answer in the result matrix. In the output, we can see that the result matrix is the addition of the two matrices.

Subtraction Matrix Program in Java:

The subtraction of the two matrices is possible only when both matrices have the same size. For example, If we want to subtract matrix B from matrix A then we can subtract each element of matrix B from the same positioned element of matrix A.

In the above example, we have taken two matrices with random integer values. In the image, we can see that the subtraction performed on each element with its corresponding element of another matrix. In the result, we can see that elements of both the matrix subtracted with their respective position in the matrix. Let’s see how to write a subtraction matrix program in java.

// subtraction matrix program in java
class HelloWorld {
    public static void main(String[] args) {
        
        // 2D natrix
        int a[][]={
                    {5,6,2},
                    {9,7,1},
                    {8,3,1}
                    };
        int b[][]={
                    {2,4,1},
                    {7,6,4},
                    {9,2,5}
                    };
                    
        int n=a.length;
        int m=a[0].length;
        
        // matrix to store the result
        int result[][]=new int[n][m];
        
        // subtraction of the matrices
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                result[i][j]=a[i][j]-b[i][j];
            }
        }
        
        System.out.println("Matrix after subtraction: ");
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                System.out.print(result[i][j]+" ");
            }
            System.out.println();
        }
    }
}

Output:

Matrix after subtraction: 
3 2 1 
2 1 -3 
-1 1 -4 

In the above program, we created two matrices of the same size with random integers. After that, we have taken a matrix result to store the answer. We used two loops and subtracted each element of matrix A from the corresponding element of matrix B. In the output, we can see that the result matrix is the addition of the two matrices.

Multiplication Matrix Program in Java:

Multiplication of the two matrices is different from addition and subtraction. To perform multiplication, we need to find the sum of the multiplication of one row and one column. For example, if we want to find the result value for the element of the first row and first column it will be the sum of the multiplication of all the elements of the row and column. Let’s understand this with an example.

In the above example, we can see that if we want to find the result[0][0] element then our answer is 52+67+2*9 which is equal to 70. Now, let’s see how the result element is at a particular position.

Now, Let’s see the conditions for the multiplication of the two matrices. If the number of rows in one matrix is equal to the number of columns in the other matrix then only we can multiply two matrices.

Let’s see in what case multiplication is possible and in what case it is not possible.

In the above example, we have matrix A of size 3×2 and matrix B of size 2×5. We can see that the number of columns in matrix A is equal to the number of rows in matrix B so multiplication is possible and the resultant matrix is of size 3×5 where 2 is the number of rows in matrix A and 5 is the number of columns in matrix B.

In the above example, the number of columns in matrix A is not equal to the number of rows in matrix B thus, the multiplication of these two matrices is not possible.

Now, let’s see how to write a code for multiplication matrix program in java.

// multiplication matrix program in java
class HelloWorld {
    public static void main(String[] args) {
        
        // 2D natrix
        int a[][]={
                    {5,6,2},
                    {9,7,1},
                    {8,3,1}
                    };
        int b[][]={
                    {2,4,1},
                    {7,6,4},
                    {9,2,5}
                    };
                    
        int n=a.length;
        int m=a[0].length;
        
        // matrix to store the result
        int result[][]=new int[n][m];
        
        // multiplication of the matrices
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                result[i][j]=0;
                for(int k=0;k<n;k++){
                    result[i][j]+=a[i][k]*b[k][j];
                }
            }
        }
        
        System.out.println("Matrix after multiplication: ");
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                System.out.print(result[i][j]+" ");
            }
            System.out.println();
        }
    }
}

Output:

Matrix after multiplication: 
70 60 39 
76 80 42 
46 52 25 

Conclusion

Matrices play a crucial role in various computational tasks, and understanding how to work with matrices is essential in programming. This article delved into the concept of matrix in Java, covering topics such as accessing matrix elements, creating a simple matrix program, and performing matrix operations like addition, subtraction, and multiplication. By providing code examples and explanations, readers gained practical insights into implementing matrix-related algorithms in Java. They learned how to iterate through matrix elements using loops, handle matrices of different sizes, and perform arithmetic operations on corresponding elements. Mastering matrices in Java expands programmers’ abilities to solve complex problems, such as solving systems of linear equations, transforming data, or performing simulations. With the knowledge gained from this article, readers are equipped to tackle a wide range of matrix-related challenges in their programming endeavors.

Frequently Asked Questions (FAQs)

Q1. How do I access a specific element in a matrix in Java?
To access a specific element in a matrix, you can use the syntax matrixName[rowIndex][columnIndex]. For example, matrix[0][0] will access the element in the first row and first column of the matrix.

Q2. Can I create a matrix with different data types in Java?
No, in Java, a matrix is a homogeneous data structure, meaning all elements must have the same data type. However, you can create matrices of different data types by using multidimensional arrays, where each array can have a different data type.

Q3. How can I perform matrix addition in Java?
To perform matrix addition in Java, you need two matrices of the same dimensions. You can iterate over each element of the matrices and add the corresponding elements together to form a new matrix that represents the sum of the two matrices.

Q4. Is it possible to multiply two matrices of different sizes in Java?
No, in order to multiply two matrices, the number of columns in the first matrix must be equal to the number of rows in the second matrix. If the dimensions of the matrices are not compatible, the multiplication operation is not possible.

Q5. How can I transpose a matrix in Java?
To transpose a matrix in Java, you can create a new matrix with swapped rows and columns. Iterate over the original matrix and assign the elements to the transposed matrix based on their new positions. The transposed matrix will have the number of rows equal to the number of columns in the original matrix and vice versa.

Leave a Reply

Your email address will not be published. Required fields are marked *