Given two matrices, A and B, where matrix A contains M rows and K columns and ma
ID: 3550453 • Letter: G
Question
Given two matrices, A and B, where matrix A contains M rows and K columns and matrix B contains K rows and N columns, the matrix product of A and B is matrix C, where C contains M rows and N columns. The entry in matrix C for row i, column j (Ci,j) is the sum of the products of the elements for row i in matrix A and column j in matrix B. That is,
C(i,j) = S( n=1 through K) A(i,n) * B(n,j)
For example, if A is a 3-by-2 matrix and B is a 2-by-3 matrix, element C3,1 is the sum of A3,1 * B1,1 and A3,2 * B2,1.
For this project, calculate each element C(i,j) of the matrix product C of two matrices A and B in a seperate thread. So the number of threads is equal to the number of terms in the matrix product. Use JAVA threads to implement this program. The matrices to be multiplied are:
Explanation / Answer
public class ParentTh {
public static final int NUM_OF_THREADS = 9;
public static void main(String args[])
{
int row;
int col;
int A[][] = {{1,4},{2,5},{3,6}};
int B[][] = {{8,7,6},{5,4,3}};
int C[][] = new int[3][3];
int threadcount = 0;
Thread[] thrd = new Thread[NUM_OF_THREADS];
try
{
for(row = 0 ; row < 3; row++)
{
for (col = 0 ; col < 3; col++ )
{
// creating thread for multiplications
thrd[threadcount] = new Thread(new WorkerTh(row, col, A, B, C));
thrd[threadcount].start(); //thread start
thrd[threadcount].join(); // joining threads
threadcount++;
}
}
}
catch (InterruptedException ie){}
// printing matrix A
System.out.println(" A Matrix : ");
&n bsp; for(row = 0 ; row < 3; row++)
{
for (col = 0 ; col < 2; col++ )
{
System.out.print(" "+A[row][col]);
}
System.out.println();
}
// printing matrix B
System.out.println(" B Matrix : ");
for(row = 0 ; row < 2; row++)
{
for (col = 0 ; col < 3; col++ )
{
System.out.print(" "+B[row][col]);
}
System.out.println();
}
// printing resulting matrix C after multiplication
System.out.println(" Resulting C Matrix : ");
for(row = 0 ; row < 3; row++)
{
for (col = 0 ; col < 3; col++ )
{
System.out.print(" "+C[row][col]);
}
System.out.println();
}
}
}
class WorkerTh implements Runnable
{
private int row;
private int col;
private int A[][];
private int B[][];
private int C[][];
public WorkerTh(int row, int col, int A[][], int B[][], int C[][] )
{
this.row = row;
this.col = col;
this.A = A;
this.B = B;
this.C = C;
}
@Override
public void run()
{
for(int k = 0; k < B.length; k++)
{
C[row][col] += A[row][k] * B[k][col];
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.