create a wrapper for cblas_sgemm that handles transposing the input matrices in swift

Here's an example of a function in Swift that provides a wrapper around cblas_sgemm and handles transposing the input matrices if necessary:

main.swift
import Accelerate

func matrixMultiplication(_ matrixA: [Float], _ matrixB: [Float], _ transposeA: Bool = false, _ transposeB: Bool = false, _ rowA: Int, _ colA: Int, _ rowB: Int, _ colB: Int) -> [Float] {

    precondition(matrixA.count == rowA * colA, "Invalid matrixA dimensions")
    precondition(matrixB.count == rowB * colB, "Invalid matrixB dimensions")
    precondition(!transposeA || rowA == colB, "Invalid matrixA dimensions for transpose")
    precondition(!transposeB || colA == rowB, "Invalid matrixB dimensions for transpose")

    let m = transposeA ? colA : rowA
    let n = transposeB ? rowB : colB
    let k = transposeA ? rowA : colA

    var result = Array(repeating: Float(0.0), count: m * n)

    cblas_sgemm(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, transposeB ? CblasTrans : CblasNoTrans, Int32(m), Int32(n), Int32(k), 1.0, matrixA, Int32(colA), matrixB, Int32(colB), 0.0, &result, Int32(n))

    return result
}
950 chars
20 lines

The function takes two input matrices matrixA and matrixB, along with the transpose flags for each matrix. The last four parameters represent the dimensions of the two matrices.

The function then performs some dimension checks to ensure that the input matrices are compatible for multiplication in their given orientation. If transpose is necessary, the function maps the dimensions accordingly.

Finally, the function calls cblas_sgemm with the appropriate arguments and returns the resulting matrix as a flat array.

gistlibby LogSnag