Kotlini programm kahe maatriksi korrutamiseks, edastades maatriksi funktsioonile

Selles programmis õpite Kotlini funktsiooni abil kahte maatriksit korrutama.

Maatriksi korrutamiseks peab esimese maatriksi veergude arv olema võrdne teise maatriksi ridade arvuga. Meie näites st

 c1 = r2

Samuti on lõpptoote maatriks suurusega r1 x c2, st

 korrutis (r1) (c2)

Saate korrutada ka kaks maatriksit ilma funktsioonideta.

Näide: Programmeerige kahe maatriksi korrutamine funktsiooni abil

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

Programmi käivitamisel on väljund järgmine:

 Kahe maatriksi summa on: 24 29 6 25 

Ülaltoodud programmis on kaks funktsiooni:

  • multiplyMatrices() mis korrutab kaks antud maatriksit ja tagastab korrutise maatriksi
  • displayProduct() mis kuvab ekraanil tootemaatriksi väljundi.

Korrutamine toimub järgmiselt:

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

Meie näites toimub see järgmiselt:

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

Siin on samaväärne Java-kood: Java-programm kahe maatriksi korrutamiseks funktsiooni abil

Huvitavad Artiklid...