Day8 矩阵乘法
1、矩阵相乘的条件就是A矩阵的列等于B矩阵的行,且最后求得的C矩阵的行和列分别为A矩阵的行、B矩阵的列;
2、二阶数组的话, a.length 表示行,a[0].length 表示列
1 import java.util.Arrays; 2 public class MatrixMultiplication { 3 /** 4 * The entrance of the program 5 * @param args 6 */ 7 public static void main(String args[]) { 8 matrixMultiplicationTest(); 9 }//Of main 10 11 /** 12 * Matrix multiplication. 13 * The columns of the first matrix should be equal to the rows of the second one. 14 * 15 * @param paraFirstMatrix 16 * @param paraSecondMatrix 17 * @return 18 */ 19 public static int[][] multiplication(int[][] paraFirstMatrix, int[][] paraSecondMatrix) { 20 int m = paraFirstMatrix.length;//Ai 21 int n = paraFirstMatrix[0].length;//Aj 22 int p = paraSecondMatrix[0].length;//Bj 23 24 //Step1. Dimension check 25 if (paraSecondMatrix.length != n) {//Bi != Aj 26 System.out.println("The two matrices cannot be multiplied."); 27 return null; 28 } 29 30 //Step2. The loop. 31 int[][] resultMatrix = new int[m][p]; 32 for (int i = 0; i < m; i++) { 33 for (int j = 0; j < p; j++) { 34 for (int k = 0; k < n; k++) { 35 resultMatrix[i][j] += paraFirstMatrix[i][k] * paraSecondMatrix[k][j]; 36 }// Of for k 37 }// Of for j 38 }// Of for i 39 return resultMatrix; 40 }// Of multiplication 41 42 /** 43 * Unit test for respective method 44 */ 45 public static void matrixMultiplicationTest() { 46 int[][]tempFirstMatrix = new int[2][3]; 47 for (int i = 0; i < tempFirstMatrix.length; i++) { 48 for (int j = 0; j < tempFirstMatrix[0].length; j++) { 49 tempFirstMatrix[i][j] = i + j; 50 }// Of for j 51 }// Of for i 52 System.out.println("The first matrix is: \r\n" + Arrays.deepToString(tempFirstMatrix)); 53 54 int[][]tempSecondMatrix = new int[3][2]; 55 for (int i = 0; i < tempSecondMatrix.length; i++) { 56 for (int j = 0; j < tempSecondMatrix[0].length; j++) { 57 tempSecondMatrix[i][j] = i*10 + j; 58 }// Of for j 59 }// Of for i 60 System.out.println("The second matrix is: \r\n" + Arrays.deepToString(tempSecondMatrix)); 61 62 int[][] tempThirdMatrix = multiplication(tempFirstMatrix, tempSecondMatrix); 63 System.out.println("The Third matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix)); 64 65 System.out.println("Try to multiply the first matrix with itself.\r\n"); 66 tempThirdMatrix = multiplication(tempFirstMatrix, tempFirstMatrix); 67 System.out.println("The result matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix)); 68 69 }// Of matrixMultiplicationTest 70 71 }// Of class MatrixMultiplication
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人