Reputation: 151
I'm new to swift and am trying to use the Accelerate framework to multiply two matrices.
However I cannot get this to work. Any help would be appreciated. Code is below:
import Accelerate
let firstMatrix :[[Float]] = [[1,2],[2,3]]
let secondMatrix : [[Float]] = [[3,2],[1,4]]
var answerMatrix :[[Float]] = [[0,0],[0,0]]
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 2, 1.0, firstMatrix, 2, secondMatrix, 2, 0.0, &answerMatrix, 2)
print(answerMatrix)
Upvotes: 0
Views: 1092
Reputation: 106317
Martin R's answer addresses your actual direct question. I want to note, though, that if you're really just working with 2x2 matrices (and not arbitrarily large matrices), you may find it easier to use the simd
module:
import simd
let firstMatrix = float2x2(rows: [[1,2],[2,3]])
let secondMatrix = float2x2(rows: [[3,2],[1,4]])
let answerMatrix = firstMatrix * secondMatrix
Upvotes: 1
Reputation: 540065
There are two problems:
cblas_dgemm()
is for "double precision matrices", i.e. the elements have the Double
type. For Float
(single-precision) matrices use cblas_sgemm()
.Example:
let firstMatrix : [Double] = [1,2 , 2,3]
let secondMatrix : [Double] = [3,2 , 1,4]
var answerMatrix : [Double] = [0,0 , 0,0]
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 2, 1.0,
firstMatrix, 2, secondMatrix, 2, 0.0, &answerMatrix, 2)
print(answerMatrix)
// [5.0, 10.0, 9.0, 16.0]
Upvotes: 3