面试题之矩阵与转置矩阵相乘

话不多说,直接上代码

 1 /**
 2  * Created with IntelliJ IDEA
 3  * Created By chump
 4  * Date: 2017/7/3
 5  * Time: 9:27
 6  */
 7 /**
 8  * 输入一个初始值,矩阵行,矩阵列,根据初始值构建矩阵,求出转置矩阵,最后求出矩阵的乘积返回
 9  * 如:输入1,3,3可构建矩阵
10  * 1    2   3
11  * 4    5   6
12  * 7    8   9
13  * 转置矩阵为
14  * 1    4   7
15  * 2    5   8
16  * 3    6   9
17  */
18 public class MatrixProduct {
19     public static void main(String []args){
20         MatrixProduct matrixProduct = new MatrixProduct();
21         matrixProduct.Matrix(1,3,3);
22     }
23     public int [][] Matrix(int initValue,int rows,int columns){
24         int init = initValue;           //初始值
25         int row = rows ;                //
26         int column = columns;           //27         //初始化矩阵
28         int [][]matrixOriginal = new int[row][column];
29         for(int i=0;i<row;i++){
30             for(int j=0;j<column;j++){
31                 matrixOriginal[i][j] = init ;
32                 init++;
33             }
34         }
35         //求转置矩阵
36         init = initValue;
37         int [][]matrixTrans = new int[column][row];
38         for(int i=0;i<column;i++){
39             for (int j=0;j<row;j++){
40                 matrixTrans[j][i] = init;
41                 init++;
42             }
43         }
44         //求矩阵乘积
45         int [][]matrixFinal = new int[row][row];
46         for (int i=0;i<row;i++){
47             for(int j=0;j<row;j++){
48                 for (int m=0;m<column;m++){
49                     matrixFinal[i][j] += matrixOriginal[i][m]*matrixTrans[m][j];
50                 }
51             }
52         }
53         for(int i=0;i<row;i++){
54             for (int j=0;j<row;j++){
55                 System.out.print(matrixFinal[i][j]+"    ");
56             }
57             System.out.println();
58         }
59      return matrixFinal;
60     }
61 }
有任何问题可以留言。
原文地址:https://www.cnblogs.com/chump-zwl/p/7109908.html