Sunday, May 1, 2011

Multiplying 2 matrices in java

See following code:

//Input number rows and columns in 2 matrices
Scanner sc = new Scanner (System.in);
int r1,c1;
System.out.print("Enter how many rows");
r1 = sc.nextInt();
System.out.print("Enter how many cols");
c1 = sc.nextInt();
int r2,c2;
System.out.print("Enter how many rows");
r2 = sc.nextInt();
System.out.print("Enter how many cols");
c2 = sc.nextInt();
if(c1 != r2){
System.out.println("Can't mult");
System.exit(1);
}
int m1[][] = new int[r1][c1];

//input m1
for (int i=0; i<r1; i++){
for (int j=0; j<c1; j++){
System.out.print("Enter element" + (i+1)+","+(j+1));
m1[i][j] = sc.nextInt();
}
}

int m2[][] = new int[r2][c2];

//input m2
for (int i=0; i<r2; i++){
for (int j=0; j<c2; j++){
System.out.print("Enter element" + (i+1)+","+(j+1));
m2[i][j] = sc.nextInt();
}
}

int m3[][] = new int[r2][c2];

//Matrix multiplication
for (int i=0; i<r1; i++){
for (int j=0; j<c2; j++){
for (int k=0; k<c1; k++){
m3[i][j]+=m1[i][k]*m2[k][j];
}
}
}

//Output m3
for (int p=0; p<r1; p++){
for (int j=0; j<c2; j++){
System.out.print(m3[p][j]+"\t");
}
System.out.println();

}

No comments:

Post a Comment

Chitika