In: Computer Science
How to write a method that performs matrix multiplication with three rectangle arrays along with their dimensions as parameters using Java programming?
import java.util.*;
public class Main
{
static int[][] matrixMultiplication(int [][]a,int [][]b,int
[][]c,int r1,int c1,int r2,int c2,int r3,int c3)
{
int [][]product1=new int[r1][c2];// product1 matrix with dimensions
r1 X c2
int i,j,k;
if(r2!=c1)//if first matrix column and second matrix row doesn't
match
{
System.out.println("First matrix and second matrix cannot be
multiplied");
return null;
}
for (i=0;i<r1;i++) {
for (j=0;j<c2;j++) {
for (k=0;k<c1;k++) {
product1[i][j]+=a[i][k]*b[k][j];
}
}
}
int [][]product2=new int[r1][c3];//final matrix with dimensions r1
X c3
if(c2!=r3)
{
System.out.println("product1 matrix and third matrix cannot be
multiplied");
return null;
}
for (i=0;i<r1;i++) {
for (j=0;j<c3;j++) {
for (k=0;k<c2;k++) {
product2[i][j]+=product1[i][k]*c[k][j];
}
}
}
return product2;
}
public static void main(String[] args) {
Scanner s=new
Scanner(System.in);
int r1,r2,r3,c1,c2,c3,i,j;
r1=s.nextInt();
c1=s.nextInt();
r2=s.nextInt();
c2=s.nextInt();
r3=s.nextInt();
c3=s.nextInt();
int [][]a=new int[r1][c1];
int [][]b=new int[r2][c2];
int [][]c=new int[r3][c3];
int [][]res=new int[r1][c3];
System.out.println("enter numbers
into matrix1");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
a[i][j]=s.nextInt();
}
}
System.out.println("enter numbers
into matrix2");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
b[i][j]=s.nextInt();
}
}
System.out.println("enter numbers
into matrix3");
for(i=0;i<r3;i++)
{
for(j=0;j<c3;j++)
{
c[i][j]=s.nextInt();
}
}
res=matrixMultiplication(a,b,c,r1,c1,r2,c2,r3,c3);
for(i=0;i<r1;i++)
{
for(j=0;j<c3;j++)
{
System.out.print(res[i][j]+"
");
}
System.out.println();
}
}
}