一、一般用二维数组表示一个矩阵。求矩阵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; }