Program Java untuk Mendarab dua Matriks dengan Meneruskan Matriks ke Fungsi

Dalam program ini, anda akan belajar memperbanyak dua matriks menggunakan fungsi di Java.

Untuk memahami contoh ini, anda harus mempunyai pengetahuan mengenai topik pengaturcaraan Java berikut:

  • Susunan Java
  • Susunan Multidimensi Java

Untuk pendaraban matriks berlaku, bilangan lajur matriks pertama mestilah sama dengan bilangan baris matriks kedua. Dalam contoh kami, iaitu

 c1 = r2

Matrik produk akhir juga berukuran r1 x c2, iaitu

 produk (r1) (c2)

Anda juga boleh mengalikan dua matriks tanpa fungsi.

Contoh: Program untuk Mendarab Dua Matriks menggunakan Fungsi

 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) ); // Mutliplying Two matrices int()() product = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2); // Displaying the result 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("Product of two matrices is: "); for(int() row : product) ( for (int column : row) ( System.out.print(column + " "); ) System.out.println(); ) ) )

Pengeluaran

 Produk dua matriks ialah: 24 29 6 25 

Dalam program di atas, terdapat dua fungsi:

  • multiplyMatrices() yang mengalikan dua matriks yang diberikan dan mengembalikan matriks produk
  • displayProduct() yang memaparkan output matrik produk di skrin.

Pendaraban berlaku seperti:

| - (a 11 xb 11 ) + (a 12 xb 21 ) + (a 13 xb 31 ) (a 11 xb 12 ) + (a 12 xb 22 ) + (a 13 xb 32 ) - | | _ (a 21 xb 11 ) + (a 22 xb 21 ) + (a 23 xb 31 ) (a 21 xb 12 ) + (a 22 xb 22 ) + (a 23 xb 32)) _ | 

Dalam contoh kami, ia berlaku sebagai:

| - (3 x 2) + (-2 x -9) + (5 x 0) = 24 (3 x 3) + (-2 x 0) + (5 x 4) = 29 - | | _ (3 x 2) + (0 x -9) + (4 x 0) = 6 (3 x 3) + (0 x 0) + (4 x 4) = 25 _ |

Artikel menarik...