Search This Blog

Showing posts with label product of matrices. Show all posts
Showing posts with label product of matrices. Show all posts

Java Program For Matrix Multiplication

This is a java program for Matrix Multiplication. To understand how it works, you should first know how matrix multiplication is done mathematically.

import java.util.Scanner;

public class MatrixMult{

public static void main(String[] args)
{
int[][] m1=new int[10][10];
int[][] m2=new int[10][10];
int[][] prod=new int[10][10];
int i,j,k,r1,c1,r2,c2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of rows and columns of first matrix:");
r1=sc.nextInt();
c1=sc.nextInt();
System.out.println("Enter number of rows and columns of second matrix:");
r2=sc.nextInt();
c2=sc.nextInt();
if(r2==c1)
    {
    System.out.println("Enter elements of First matrix (row wise):");
    for(i=0;i<r1;i++)
        for(j=0;j<c1;j++)
            m1[i][j]=sc.nextInt();
    System.out.println("Matrix1 is :");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c1;j++)
            System.out.printf("%d ",m1[i][j]);
        System.out.printf("\n");
        }
    System.out.println("Enter elements of Second matrix (row wise):");
    for(i=0;i<r2;i++)
        for(j=0;j<c2;j++)
            m2[i][j]=sc.nextInt();
    System.out.println("Matrix2 is:");
    for(i=0;i<r2;i++)
        {
        for(j=0;j<c2;j++)
            System.out.printf("%d ",m2[i][j]);
        System.out.printf("\n");
        }
    System.out.println("Product of the Matrices (M1 x M2):");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c2;j++)
            {
            prod[i][j]=0;
            for(k=0;k<r1;k++)
                prod[i][j]+=m1[i][k]*m2[k][j];
            System.out.printf("%d ",prod[i][j]);
            }
        System.out.print("\n");
        }
    }
else
    {
    System.out.println("Matrices can't be multiplied.");
    System.out.print("No. of columns of first matrix and no of rows of second are different.");
    }
}
}

Output

Enter number of rows and columns of first matrix:
2
2
Enter number of rows and columns of second matrix:
2
2
Enter elements of First matrix (row wise):
5
8
6
4
Matrix1 is :
5 8 
6 4 
Enter elements of Second matrix (row wise):
5
6
8
9
Matrix2 is:
5 6 
8 9 
Product of the Matrices (M1 x M2):
89 102 
62 72