Kotlinov program za množenje dveh matrik s prenašanjem matrike v funkcijo

V tem programu se boste naučili množiti dve matriki s pomočjo funkcije v Kotlinu.

Za množenje matrike mora biti število stolpcev prve matrice enako številu vrstic druge matrike. V našem primeru, tj

 c1 = r2

Tudi matrika končnega izdelka je velikosti r1 x c2, tj

 izdelek (r1) (c2)

Dve matriki lahko tudi pomnožite brez funkcij.

Primer: Program z množenjem dveh matrik z uporabo funkcije

 fun main(args: Array) ( val r1 = 2 val c1 = 3 val r2 = 3 val c2 = 2 val firstMatrix = arrayOf(intArrayOf(3, -2, 5), intArrayOf(3, 0, 4)) val secondMatrix = arrayOf(intArrayOf(2, 3), intArrayOf(-9, 0), intArrayOf(0, 4)) // Mutliplying Two matrices val product = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2) // Displaying the result displayProduct(product) ) fun multiplyMatrices(firstMatrix: Array, secondMatrix: Array, r1: Int, c1: Int, c2: Int): Array ( val product = Array(r1) ( IntArray(c2) ) for (i in 0… r1 - 1) ( for (j in 0… c2 - 1) ( for (k in 0… c1 - 1) ( product(i)(j) += firstMatrix(i)(k) * secondMatrix(k)(j) ) ) ) return product ) fun displayProduct(product: Array) ( println("Product of two matrices is: ") for (row in product) ( for (column in row) ( print("$column ") ) println() ) )

Ko zaženete program, bo rezultat:

 Vsota dveh matrik je: 24 29 6 25 

V zgornjem programu sta dve funkciji:

  • multiplyMatrices() ki pomnoži dve dani matriki in vrne matriko izdelka
  • displayProduct() ki na zaslonu prikaže izhod matrike izdelka.

Množenje poteka kot:

| - (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) _ | 

V našem primeru to poteka kot:

| - (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 _ |

Tu je enakovredna koda Java: program Java za pomnožitev dveh matrik z uporabo funkcije

Zanimive Članki...