Write a method called matmul that takes as arguments two matrices of doubles: do
ID: 3767479 • Letter: W
Question
Write a method called matmul that takes as arguments two matrices of doubles: double[][] A and double[][] B, and returns the matrix that represents the multiplication of the two argument matrices (that is C = AB). Matrix multiplication is not commutative and it works as follows: one can only multiply two matrices if the number of rows of the left matrix is the same as the number of columns of the right matrix. The entry (i; j) on C = AB is obtained by taking the inner-product of the ith row of A with the jth column of B. The inner-product between two vectors is obtained by adding up the products of the respective entries in the two vectors.
Explanation / Answer
class matrix_multi
{
public static void matrixMultiply(double[][] m, double[][] n)
{
double[][] multipliedMatrix = new double [m.length][n[0].length];
for (int i=0; i<m.length; i++)
{
for (int j=0; j<n[0].length; j++)
{
for (int k=0; k<n.length; k++)
{
multipliedMatrix[i][j] = multipliedMatrix[i][j] + (m[i][k] * n[k][j]);
}
}
}
for (int i=0; i<m.length; i++)
{
for (int k=0; k<n.length; k++)
{
System.out.println(multipliedMatrix[i][k]);
}
}
}
public static void main(String args[])
{
int i,j,c=1;
double a[][] =new double[3][3];
double b[][] = new double[3][3];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=c;
b[i][j]=c+2;
c++;
}
}
matrixMultiply(a,b);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.