0.主题
今天的主题是矩阵乘法,如果两个矩阵满足前一个矩阵的列数与后一个矩阵的行数相等,就可以做乘法。结果矩阵第i行j列的元素为第一个矩阵的第i行元素与第二个矩阵的第j列元素对应值做乘法再求和。
例如,一个m行n列的矩阵A和一个n行p列的矩阵B做乘法得到一个m行p列的矩阵C可以表示如下:
C
i
j
=
∑
k
=
1
n
A
i
k
B
k
j
C_{ij}=\sum_{k=1}^{n}A_{ik}B_{kj}
Cij=k=1∑nAikBkj
1.矩阵乘法
程序代码如下,在进行矩阵乘法之前需要先判断两个矩阵能否做乘,若不能,程序应该给出相应的反馈。
package basic;
import java.util.Arrays;
public class MatrixMultiplication {
/**
******************
* The entrance of the program.
*
* @param args Not used now.
******************
*/
public static void main( String args[ ] ) {
matrixMultiplicationTest( );
} // Of main
/**
******************
* Matrix multiplication. The columns of the first matrix should be equal to the rows of the second one.
*
* @param paraFirstMatrix The first matrix.
* @param paraSecondMatrix The second matrix.
* @return The result matrix.
******************
*/
public static int[ ][ ] multiplication( int [ ][ ] paraFirstMatrix, int[ ][ ] paraSecondMatrix ){
int m = paraFirstMatrix.length;
int n = paraFirstMatrix[ 0 ].length;
int p = paraSecondMatrix[ 0 ].length;
// Step 1. Dimension check.
if( paraSecondMatrix.length != n ) {
System.out.println("The two matrices cannot be multiplied.");
return null;
} // Of if
// Step 2. The loop.
int[ ][ ] resultMatrix = new int[ m ][ p ];
for( int i = 0; i < m; i++ ) {
for( int j = 0; j < p; j++ ) {
for( int k = 0; k < n; k++ ) {
resultMatrix[ i ][ j ] += paraFirstMatrix[ i ][ k ] * paraSecondMatrix[ k ][ j ];
} // Of for k
} // Of for j
} // Of for i
return resultMatrix;
} // Of multiplication
/**
******************
* Unit test for respective method.
******************
*/
public static void matrixMultiplicationTest( ) {
int[ ][ ] tempFirstMatrix = new int[ 2 ][ 3 ];
for( int i = 0; i < tempFirstMatrix.length; i++ ) {
for( int j = 0; j < tempFirstMatrix[ 0 ].length; j++ ) {
tempFirstMatrix[ i ][ j ] = i + j;
} // Of for j
} // Of for i
System.out.println("The first matrix is: \r\n" + Arrays.deepToString(tempFirstMatrix) );
int[ ][ ] tempSecondMatrix = new int[ 3 ][ 2 ];
for( int i = 0; i < tempSecondMatrix.length; i++ ) {
for( int j = 0; j < tempSecondMatrix[ 0 ].length; j++ ) {
tempSecondMatrix[ i ][ j ] = i * 10 + j;
} // Of for j
} // Of for i
System.out.println("The second matrix is: \r\n" + Arrays.deepToString(tempSecondMatrix) );
int[ ][ ] tempThirdMatrix = multiplication( tempFirstMatrix, tempSecondMatrix );
System.out.println("The third matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix) );
System.out.println("Trying to multiply the first matrix with itself.\r\n");
tempThirdMatrix = multiplication( tempFirstMatrix, tempFirstMatrix );
System.out.println("The result matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix) );
} // Of matrixMultiplicationTest
} // Of class MatrixMultiplication
程序的执行结果如下
可以看到,当程序输入合法时,程序返回正确的矩阵乘法结果,当输入非法时,程序给出了两矩阵不能做乘的提示。
2.其他
- 应当考虑到程序的非法输入,保证算法的健壮性
- 此处矩阵乘法用了三重for循环,对于一个M行N列的矩阵和一个N行P列的矩阵相乘,此处时间复杂度达 O ( M N P ) O(MNP) O(MNP),相当高了
- java中创建一个数字数组时,所有元素都初始化为0