使用加速框架的Swift中的矩阵求逆

Nic*_*las 3 xcode linear-algebra matrix-inverse ios swift

按照我在这里找到的好的指示:https://github.com/haginile/SwiftAccelerate我验证了矩阵反转是有效的.事实上它确实给出了给出的例子.但是我得到EXC_BAD_ACCESS任何其他矩阵(大于2x2)的错误,例如下面的2D矩阵(转换为1D数组)已成功在matlab和python中测试过,它不起作用

m = [0.55481645013013, -1.15522603580724, 0.962090414322894, -0.530226035807236, 0.168545207161447, -0.38627124296868, 0.93401699437494, -0.999999999999995, 0.684016994374945, -0.23176274578121, 0.123606797749979, -0.323606797749979, 0.432893622827287, -0.323606797749979, 0.123606797749979, 0.231762745781211, -0.684016994374948, 1.0, -0.934016994374947, 0.386271242968684, 0.168545207161448, -0.530226035807237, 0.962090414322895, -1.15522603580724, 0.554816450130132]
Run Code Online (Sandbox Code Playgroud)

它的倒置矩阵应该是

inv(AA)

ans =

  Columns 1 through 3

          -262796763616197          -656991909040516          4.90007819375216
          -162417332048282          -406043330120712          14.6405748712708
         0.718958226823704          7.87760147961979          30.4010295628018
           162417332048287           406043330120730          46.1614842543337
           262796763616208           656991909040536          55.9019809318537

  Columns 4 through 5

          -656991909040528           262796763616211
          -406043330120721           162417332048287
         -4.28281034550088        -0.718958226823794
           406043330120704          -162417332048283
           656991909040497          -262796763616196
Run Code Online (Sandbox Code Playgroud)

你能否在Swift中给我另一种矩阵求逆方法?或者解释一下如何解决这个问题?我真的不明白为什么它不起作用.

Ste*_*non 9

它不起作用,因为您找到的说明不太好.具体来说,枢轴和工作空间都需要是数组,而不是标量值; 它只是偶然机会用于2乘2矩阵.

以下是invert正确分配工作空间的函数的修改版本:

func invert(matrix : [Double]) -> [Double] {
  var inMatrix = matrix
  var N = __CLPK_integer(sqrt(Double(matrix.count)))
  var pivots = [__CLPK_integer](count: Int(N), repeatedValue: 0)
  var workspace = [Double](count: Int(N), repeatedValue: 0.0)
  var error : __CLPK_integer = 0
  dgetrf_(&N, &N, &inMatrix, &N, &pivots, &error)
  dgetri_(&N, &inMatrix, &N, &pivots, &workspace, &N, &error)
  return inMatrix
}
Run Code Online (Sandbox Code Playgroud)

我还应该注意到你的5x5矩阵是非常恶劣的,所以即使你可以计算"逆",该计算的误差也会非常大,并且实际上不应该使用逆.

一个Swift 4版本:

func invert(matrix : [Double]) -> [Double] {
    var inMatrix = matrix
    var N = __CLPK_integer(sqrt(Double(matrix.count)))
    var pivots = [__CLPK_integer](repeating: 0, count: Int(N))
    var workspace = [Double](repeating: 0.0, count: Int(N))
    var error : __CLPK_integer = 0

    withUnsafeMutablePointer(to: &N) {
        dgetrf_($0, $0, &inMatrix, $0, &pivots, &error)
        dgetri_($0, &inMatrix, $0, &pivots, &workspace, $0, &error)
    }
    return inMatrix
}
Run Code Online (Sandbox Code Playgroud)

  • @StephenCanon:我冒昧地添加了一个Swift 4版本,希望你不要介意. (4认同)