如何使用加速框架执行矩阵逆运算? [英] How to perform matrix inverse operation using the accelerate framework?
问题描述
我想找到矩阵的逆。
我知道这首先涉及LU分解,然后进行反演步骤,但我无法通过搜索apple的来找到所需的函数。 10.7的文档!
I know this involves first LU factorisation then the inversion step but I cannot find the required function by searching apple's docs of 10.7!
这似乎是一个有用的帖子使用CBLAS / LAPACK在C中进行对称矩阵求逆,指出 sgetrf _
和 sgetri _
应该使用函数。但是搜索这些术语在Xcode文档中什么也没找到。
This seems like a useful post Symmetric Matrix Inversion in C using CBLAS/LAPACK, pointing out that the sgetrf_
and sgetri_
functions should be used. However searching these terms I find nothing in Xcode docs.
有人对这种矩阵运算有样板代码吗?
Does anybody have boiler plate code for this matrix operation?
推荐答案
Apple根本没有记录LAPACK代码,因为它们只是实现了 netlib.org 。很遗憾您无法从内置的Xcode文档中搜索这些函数名称,但是解决方案非常简单:只需在URL中指定函数名称,例如对于 dgetrf _()
,请转到 http://www.netlib.org/clapack/what/double/dgetrf.c 。
Apple does not document the LAPACK code at all, I guess because they just implement the standard interface from netlib.org. It's a shame that you cannot search the these function names from the built-in Xcode docs, however the solution is fairly straight forward: just specify the function name in the URL e.g. for dgetrf_()
go to, http://www.netlib.org/clapack/what/double/dgetrf.c.
要反转矩阵,需要两个LAPACK函数: dgetrf _()
执行LU分解,而 dgetri _()
获取上一个函数的输出并执行实际反演。
To invert a matrix two LAPACK function are need: dgetrf_()
, which performs LU factorisation, and dgetri_()
which takes the output of the previous function and does the actual inversion.
我使用Xcode创建了一个标准应用程序项目,添加了Accelerate Framework,创建了两个C文件:matinv.h,matinv.c并编辑了main.m文件以将其删除可可的东西:
I created a standard Application Project using Xcode, added the Accelerate Framework, create two C files: matinv.h, matinv.c and edited the main.m file to remove Cocoa things:
// main.m
#import "matinv.h"
int main(int argc, char *argv[])
{
int N = 3;
double A[N*N];
A[0] = 1; A[1] = 1; A[2] = 7;
A[3] = 1; A[4] = 2; A[5] = 1;
A[6] = 1; A[7] = 1; A[8] = 3;
matrix_invert(N, A);
// [ -1.25 -1.0 3.25 ]
// A^-1 = [ 0.5 1.0 -1.5 ]
// [ 0.25 0.0 -0.25 ]
return 0;
}
现在是头文件,
// matinv.h
int matrix_invert(int N, double *matrix);
然后是源文件,
int matrix_invert(int N, double *matrix) {
int error=0;
int *pivot = malloc(N*sizeof(int)); // LAPACK requires MIN(M,N), here M==N, so N will do fine.
double *workspace = malloc(N*sizeof(double));
/* LU factorisation */
dgetrf_(&N, &N, matrix, &N, pivot, &error);
if (error != 0) {
NSLog(@"Error 1");
free(pivot);
free(workspace);
return error;
}
/* matrix inversion */
dgetri_(&N, matrix, &N, pivot, workspace, &N, &error);
if (error != 0) {
NSLog(@"Error 2");
free(pivot);
free(workspace);
return error;
}
free(pivot);
free(workspace);
return error;
}
这篇关于如何使用加速框架执行矩阵逆运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!