1. 程式人生 > >Java實現矩陣運算

Java實現矩陣運算

      在做大資料或人工智慧開發的過程做難免會遇到矩陣運算,本文在這裡給大家實現一個簡單的矩陣運算,請看下程式碼:

package test;

/**
 * 矩陣運算
 * 
 * @author Administrator
 *
 */
public class MatrixOperation {
	/**
	 * 自動填充矩陣,將不足的行後自動補0
	 * 
	 * @param M
	 * @return
	 */
	public static int[][] fillMatrix(int[][] M) {
		int ml = 0;// 最長行
		for (int i = 0; i < M.length; i++) {
			ml = ml < M[i].length ? M[i].length : ml;
		}
		int Nm[][] = new int[M.length][ml];
		for (int i = 0; i < M.length; i++) {
			for (int j = 0; j < M[i].length; j++) {
				Nm[i][j] = M[i][j];
			}
		}
		return Nm;
	}

	/**
	 * 矩陣乘法A*B
	 * 
	 * @param A
	 * @param B
	 * @return
	 * @throws Exception
	 */
	public static int[][] multiplication(int[][] A, int[][] B) throws Exception {
		// 先判斷A矩陣的列是否等於B矩陣的行,A矩陣與B矩陣可以進行乘法運算的條件就是A的列數等於B的行數
		A = fillMatrix(A);
		B = fillMatrix(B);
		if (A[0].length != B.length) {
			throw new Exception("矩陣A的列不等於矩陣B的行!");
		}
		int C[][] = new int[A.length][B[0].length];
		for (int i = 0; i < A.length; i++) {
			for (int j = 0; j < B[i].length; j++) {
				for (int k = 0; k < A[i].length; k++) {
					C[i][j] += A[i][k] * B[k][j];
				}
			}
		}
		return C;
	}

	/**
	 * 矩陣轉置
	 * 
	 * @param A
	 * @return
	 */
	public static int[][] transposed(int[][] A) {
		A = fillMatrix(A);
		int[][] AT = new int[A[0].length][A.length];
		for (int i = 0; i < AT.length; i++) {
			for (int j = 0; j < AT[0].length; j++) {
				AT[i][j] = A[j][i];
			}
		}
		return AT;
	}
}

測試寫的方法,構建矩陣A,B

	/**
	 * 測試矩陣運算
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		int A[][] = { { 1, 2, 0 }, { 3, 4, 0 }, { 5, 6, 0 } };
		int B[][] = { { 1, 2, 3, 1 }, { 3, 2 }, {} };
		try {
			int C[][] = multiplication(A, B);// 矩陣乘法
			for (int i = 0; i < C.length; i++) {
				for (int j = 0; j < C[0].length; j++) {
					System.out.print(C[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println("**********************");
			int CT[][] = transposed(C);// 矩陣轉置
			for (int i = 0; i < CT.length; i++) {
				for (int j = 0; j < CT[0].length; j++) {
					System.out.print(CT[i][j] + " ");
				}
				System.out.println();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

運算結果: