swift - 在 Swift 中使用 cblas_dgemm 进行矩阵乘法时遇到问题

标签 swift matrix matrix-multiplication accelerate-framework

我是 swift 的新手,正在尝试使用 Accelerate 框架将两个矩阵相乘。

但是我无法让它工作。任何帮助,将不胜感激。代码如下:

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)

最佳答案

有两个问题:

  • cblas_dgemm() 用于“ double 矩阵”,即元素具有 Double 类型。对于 Float(单精度)矩阵,使用 cblas_sgemm()
  • 每个矩阵都必须作为指向一维数组的指针传递给函数。

例子:

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]

关于swift - 在 Swift 中使用 cblas_dgemm 进行矩阵乘法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241457/

相关文章:

c++ - |9|错误 : invalid use of non-static data member 'Matrix::row' |9|error: array bound is not an integer constant before ']' token|

swift - 不可变类型只有可变成员

ios - Tableviewcell 应该知道它是否在应用程序加载时被选择 - iOS swift

ios - 以编程方式配置最大项目间间距(swift 3.0)

matrix - 为什么像 gem 迷阵这样的 n×n 矩阵游戏中有 n-1 个不同的对象?

opengl - 我可以使用 OpenGL 进行通用矩阵乘法吗?

go - 使用 goroutine 进行矩阵乘法会降低性能

ios - Swift:为不同的选项卡设置不同的导航栏按钮

r - 从矩阵中提取一行

python - numpy.concatenation 的问题