user5672373
user5672373

Reputation: 151

Trouble using cblas_dgemm for matrix multiplication in Swift

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

Answers (2)

Stephen Canon
Stephen Canon

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

Martin R
Martin R

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().
  • Each matrix must be passed to the function as a pointer to a one-dimensional array.

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

Related Questions