矩阵相乘
Posted 辰峰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了矩阵相乘相关的知识,希望对你有一定的参考价值。
矩阵相乘
代码如下:
package Day05;
public class MtxMultiplyDemo {
public static void main(String[] args) {
//初始化mtx A
int[][] mtxA = new int[][]{{1,2},{3,4}};
//初始化mtx B
int[][] mtxB = new int[][]{{3,4},{5,6}};
//初始化mtx C 先赋值为null,只给一个int[][]类型模板
int[][] mtxC = null;
//mtxA * mtxB = mtxC
mtxC = mtxMultiply(mtxA, mtxB);
// 打印矩阵mtx
printMtx(mtxA);
printMtx(mtxB);
printMtx(mtxC);
}
/**
* 打印矩阵mtx
* @param mtx
*/
private static void printMtx(int[][] mtx) {
for (int i = 0; i < mtx.length; i++) {
for (int j = 0; j < mtx[i].length; j++) {
System.out.print(mtx[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
}
/**
* mtxA * mtxB = mtxResult
* @param mtxA
* @param mtxB
* @return mtxResult
*/
private static int[][] mtxMultiply(int[][] mtxA, int[][] mtxB) {
int[][] mtxResult = new int[mtxA.length][mtxB[0].length];
//矩阵相乘的核心算法
for (int i = 0; i < mtxResult.length; i++) {
for (int j = 0; j < mtxResult[i].length; j++) {
for (int k = 0; k < mtxB.length; k++) {
mtxResult[i][j] += mtxA[i][k] * mtxB[k][j];
}
}
}
return mtxResult;
}
}
以上是关于矩阵相乘的主要内容,如果未能解决你的问题,请参考以下文章