矩陣乘法和矩陣的冪

一、一般用二維數組表示一個矩陣。求矩陣M和矩陣N相乘,要求M的列和N的行相等,即矩陣M的列數等於java

M[0].length;矩陣N的行數等於N.length;即M[0].length=N.length時,兩個矩陣才能進行乘法運算,不然不能相乘,獲得的結果是M.length行N[0].length列的。下面是求兩個矩陣相乘的代碼:數組

public class Test {
	public static void main(String[] args) {
		int[][]m = {{2,2},{2,2}};
		int[][]n = {{2,2,2},{3,3,3}};
		int[][]res = mutilMatrix(m, n);
		for(int i=0;i<res.length;i++){
			for(int j=0;j<res[0].length;j++){
				System.out.print(res[i][j]+" ");
			}
			System.out.println();
		}
	}
	
	public static int[][] mutilMatrix(int[][]m,int[][]n){//矩陣乘法。
		int[][]res = new int[m.length][n[0].length];
		for(int i=0;i<m.length;i++){
			for(int j=0;j<n[0].length;j++){
				for(int k=0;k<n.length;k++){
					res[i][j]+=m[i][k]*n[k][j];
				}
			}
		}
		return res;
	}
}
結果爲:
10 10 10 
10 10 10

二、矩陣M的P次冪code

public static int[][] matrixPower(int[][]m,int p){
		int[][]res = new int[m.length][m[0].length];
		//先將結果矩陣設爲單位陣,一個矩陣乘以單位陣等於這個矩陣自己。
		for(int i=0;i<m.length;i++){
				res[i][i] = 1;
		}
		int[][]temp = m;
		while(p!=0){
			if(p==1){
				res = mutilMatrix(res, temp);
				p = 0;
			}
			temp = mutilMatrix(temp, temp);
			p = p/2;
		}
		/*for(;p!=0;p>>=1){
			if((p&1)!=0){
				res = mutilMatrix(res, temp);
			}
			temp = mutilMatrix(temp, temp);
		}*/
		return res;
	}
相關文章
相關標籤/搜索