Pages

Tuesday, 23 April 2013

Java code to multiply two matrices

/*
Program to read 2 matrices from user & find their product.
*/
import java.io.*;
class multiplication
{
int a[][];
int m,n;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public multiplication(int x,int y) // Constructor
{
a = new int[x][y];
m = x;
n = y;
}
public static void main(String args[]) throws IOException
{
// Read no. of rows & columns in the matrices
System.out.print("Enter no. of rows in 1st matrix : ");
int m1 = Integer.parseInt(br.readLine());
System.out.print("Enter no. of columns in 1st matrix : ");
int n1 = Integer.parseInt(br.readLine());
System.out.print("Enter no. of rows in 2nd matrix : ");
int m2 = Integer.parseInt(br.readLine());
System.out.print("Enter no. of columns in 2nd matrix : ");
int n2 = Integer.parseInt(br.readLine());
if(n1!=m2)
{
System.out.println("\nThe Matrices are incompatible for
Multiplication !");
System.exit(1);
}
// Read Matrices
System.out.println("\nEnter the values for 1st Matrix :");
multiplication p = new multiplication(m1,n1);
p.populateMatrix(m1,n1);
System.out.println("\nEnter the values for 2nd Matrix :");
multiplication q = new multiplication(m2,n2);
q.populateMatrix(m2,n2);
9// Multiply Matrices
multiplication call = new multiplication(m1,n2);
call.multiply(p,q);
// Display the product matrix
System.out.println("\nThe Product Matrix is :");
call.printMatrix(call);
}
public void populateMatrix(int x,int y) throws IOException
{
for(int i=0;i<x;i++)
{
System.out.println("\nRow " +(i+1));
for(int j=0;j<y;j++)
a[i][j] = Integer.parseInt(br.readLine());
}
}
public void multiply(multiplication p,multiplication q)
{
for(int i=0;i<p.m;i++)
{
for(int j=0;j<q.n;j++)
{
a[i][j] = 0;
for(int k=0;k<p.n;k++)
a[i][j] += p.a[i][k]*q.a[k][j];
}
}
}
public void printMatrix(multiplication p)
{
for(int i=0;i<p.m;i++)
{
System.out.println();
for(int j=0;j<p.n;j++)
System.out.print(a[i][j] +" ");
}
}
}
/**
* ALGORITHM :
* ---------
* 1. Start
* 2. Construct two double-dimensional arrays of appropriate size.
* 3. Fill the arrays with data entries.
* 4. Check if the arrays are compatible for multiplication.
10* 5. Multiply the arrays.
* 6. Print the product array.
* 7. End
*/
/*
OUTPUT :
------
Enter
Enter
Enter
Enter
no.
no.
no.
no.
of
of
of
of
rows in
columns
rows in
columns
1st matrix : 3
in 1st matrix : 2
2nd matrix : 2
in 2nd matrix : 4
Enter the values for 1st Matrix :
Row 1
4
2
Row 2
1
3
Row 3
9
6
Enter the values for 2nd Matrix :
Row 1
8
4
5
7
Row 2
3
2
11
8
The Product Matrix is :
38 20
17 10
90 48
*/
42 44
38 31
111 111
*/


No comments:

Post a Comment

Back to Top