stothers matrix multiplication in swift

Here's an example code for matrix multiplication in Swift using nested loops:

main.swift
func multiplyMatrices(_ a: [[Int]], _ b: [[Int]]) -> [[Int]]? {
    if a[0].count != b.count { // check if matrices can be multiplied
        return nil
    }
    
    let resultRows = a.count
    let resultColumns = b[0].count
    let intermediateColumns = b.count
    var result = Array(repeating: Array(repeating: 0, count: resultColumns), count: resultRows)
    
    for i in 0..<resultRows {
        for j in 0..<resultColumns {
            for k in 0..<intermediateColumns {
                result[i][j] += a[i][k] * b[k][j]
            }
        }
    }
    
    return result
}

let a = [[1, 2, 3], [4, 5, 6]]
let b = [[1, 2], [3, 4], [5, 6]]
let result = multiplyMatrices(a, b)
print(result!) // Output: [[22, 28], [49, 64]]
734 chars
26 lines

The multiplyMatrices function takes two matrices a and b as parameters and returns their product. It first checks if the matrices can be multiplied by comparing the number of columns of the first matrix a with the number of rows of the second matrix b.

Then, it initializes an empty 2D array for the result with the appropriate number of rows and columns. It then loops through the rows of the first matrix a, the columns of the second matrix b, and the common dimension (columns of a and rows of b) to calculate the dot product of the corresponding row of a and column of b, and stores it in the appropriate position in the result matrix.

Finally, it returns the result matrix. The example code also demonstrates how to call this function with sample matrices and print the resulting product.

gistlibby LogSnag