English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
في هذا البرنامج، ستتعلم كيفية استخدام الوظائف في Java لضرب مصفوفتين
من أجل إجراء ضرب مصفوفات، يجب أن يكون عدد الأعمدة في المصفوفة الأولى مساوياً لعدد الصفوف في المصفوفة الثانية. في مثالنا، أي
c1 = r2
حجم مصفوفة التراكم النهائية هو r1 x c2، أي
product[r1][c2]
يمكنك أيضًاMultiplying two matrices without functions。
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 = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2); // عرض النتيجة displayProduct(product); } public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix, int r1, int c1, int c2) { 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]; } } } return product; } public static void displayProduct(int[][] product) { System.out.println("ناتج الضرب بين المصففيين هو: "); for(int[] row : product) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
عند تشغيل هذا البرنامج، الناتج هو:
ناتج الضرب بين المصففيين هو: 24 29 6 25
في البرنامج المذكور أعلاه، هناك وظيفتان:
multiplyMatrices() - يضربان مصففيان مقدمين ويقوم بتحويل مصففي الناتج
displayProduct() - Display the output of the product matrix on the screen.
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 _|