How to implement matrix multiplication in Swift

1 Answer

0 votes
import Foundation

// Multiply rows of A by columns of B.

typealias Matrix = [[Int]]

// Print a 2D array (matrix)
func printMatrix(_ arr2d: Matrix) {
    for row in arr2d {
        for value in row {
            // "%4d" formatting equivalent in Swift
            let formatted = String(format: "%4d", value)
            print(formatted, terminator: "")
        }
        print()
    }
}

// Multiply matrices A and B into C
func multipleMatrix(a: Matrix, b: Matrix, c: inout Matrix) {
    for i in 0..<c.count {
        for j in 0..<c[i].count {
            for k in 0..<a[i].count {
                c[i][j] += a[i][k] * b[k][j]
            }
        }
    }
}

func main() {
    // Create matrices
    let a: Matrix = [
        [1, 8, 5],
        [6, 7, 1],
        [8, 7, 6]
    ]

    let b: Matrix = [
        [4, 8, 1],
        [6, 5, 3],
        [4, 6, 5]
    ]

    // Initialize result matrix C with zeros
    var c: Matrix = Array(
        repeating: Array(repeating: 0, count: b[0].count),
        count: a.count
    )

    // c[0][0] = (a[0][0] * b[0][0]) + (a[0][1] * b[1][0]) + (a[0][2] * b[2][0])

    printMatrix(a)
    print()
    printMatrix(b)
    print()

    multipleMatrix(a: a, b: b, c: &c)

    printMatrix(c)
}

main()


/*
run:
        
     1   8   5
     6   7   1
     8   7   6
    
     4   8   1
     6   5   3
     4   6   5
    
    72  78  50
    70  89  32
    98 135  59
    
*/

 



answered 2 days ago by avibootz
...