Programming and Problem Solving with Java

(やまだぃちぅ) #1
[(H1L)] | 611

Let’s make dotProductbe a helper function.

publicMatrix multiply(Matrix two) throwsMatException
// Returns matrix times two.matrix
{
if (matrix[0].length != two.matrix.length)
throw newMatException("Illegal matrix multiplication.");
else
{
Matrix result =
new Matrix(matrix.length, two.matrix[0].length);
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < two.matrix[0].length; col++)
{
result.matrix[row][col] = dotProduct(row,col,two);
}
returnresult;
}
}


private doubledotProduct(int row, int col, Matrix two)
// Returns the dot product of row of matrix and column of two.matrix
{
doubletotal = 0;
for (int index = 0; index < two.matrix.length; index++)
total = total + matrix[row][index]*two.matrix[index][col];
returntotal;
}


dotProduct(row, col, two)
Set total to 0
forindex going from 0 through number of rows of two
Set total to matrix[row][index] * two.matrix[index][col]+ total

multiply (two)
ifmultiplication is not legal
throw MatException
else
Create result matrix with number of rows in matrix and number of columns in
two.matrix
forrow going from 0 through matrix.length  1
forcol going from 0 through two.matrix[0].length  1
Set result[row][col] to dot product of row of matrix
and col of two.matrix
Free download pdf