English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习使用Java中的多维数组将两个矩阵相乘。
为了进行矩阵乘法,第一矩阵的列数必须等于第二矩阵的行数。在我们的示例中,即
c1 = r2
最终积矩阵的大小为r1 x c2,即
product[r1][c2]
您还可以Using a function to multiply two matrices。
public class MultiplyMatrices { public static void main(String[] args) { int r1 = 2, c1 = 3; int r2 = 3, c2 = 2; int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} }; int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} }; // 两个矩阵相乘 int[][] product = new int[r1][c2]; for(int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { for (int k = 0; k < c1; k++) { product[i][j] += firstMatrix[i][k] * secondMatrix[k][j]; } } } //显示结果 System.out.println("两个矩阵的总和为: "); for(int[] row : product) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
عند تشغيل هذا البرنامج، الناتج هو:
مجموع مجموعتين من المعادلات هو: 24 29 6 25
In the above program, the multiplication occurs as follows:
|- (a11 × b11) + (a12 × b21) + (a13 × b31) (a11 × b12) + (a12 × b22) + (a13 × b32) -| |_ (a21 × b11) + (a22 × b21) + (a23 × b31) (a21 × b12) + (a22 × b22) + (a23 × b32) _|
In our example, it occurs as follows:
|- (3 × 2) + (-2 × -9) + (5 × 0) = 24 (3 × 3) + (-2 × 0) + (5 × 4) = 29 -| |_ (3 × 2) + (0 × -9) + (4 × 0) = 6 (3 × 3) + (0 × 0) + (4 × 4) = 25 _|