1. 程式人生 > >矩陣相乘

矩陣相乘

ati xmu args main public void package ply 打印

矩陣相乘

代碼如下:

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;
}
}

矩陣相乘