Next: Example: sums of the Up: Unit 07 Previous: Example: sum of two

## Example: product of two matrices

We develop a static method, matrixProduct(), that takes as parameters two matrices A and B of doubles and returns a new matrix obtained as the product of A and B. Assume that the matrices are square, i.e., they have the same numbers of rows and columns, and that A and B have the same dimensions.

Recall that, if C is the product of A and B, then the generic element C[i][j] is the scalar product row i of A with column j of B, i.e., C[i][j] = (A[i][k]*B[k][j]).

public static double[][] matrixProduct(double[][] A, double[][] B) {
double[][] C = new double [A.length][A[0].length];
for (int i = 0; i < A.length; i++)
for (int j = 0; j < A[0].length; j++) {
C[i][j] = 0;
for (int k = 0; k < A[0].length; k++)
C[i][j] += A[i][k] * B[k][j];
}
return C;
}


Note that, in order to calculate the product of the matrices A and B, we use three nested for loops: the outermost loop iterates over the rows (i) of C, the intermediate loop iterates over the columns (j) of C, while the innermost loop calculates the scalar product of row i of A with column j of B, and assigns the calculated value to C[i][j].

Example of usage:

public static void main(String[] args) {
double[][] A = {            // creates matrix A of dimension 3x3
{ 1.0, 2.0, 2.0 },
{ 7.0, 5.0, 9.0 },
{ 3.0, 0.0, 6.0 }
};
double[][] B = {            // creates matrix B of dimension 3x3
{ 5.0, 4.0, 1.0 },
{ 1.0, 0.0, 3.0 },
{ 7.0, 5.0, 2.0 }
};

double[][] C = matrixProduct(A,B); // calculates the product A*B
System.out.println(C[1][0]);  // prints 103.0 (obtained as
// 7.0*5.0 + 5.0*1.0 + 9.0*7.0)
}


Next: Example: sums of the Up: Unit 07 Previous: Example: sum of two