轉載請注明出處:
http://www.cnblogs.com/darkknightzh/p/5578027.html
參考文檔:mkl的說明文檔
lapack_int LAPACKE_sgesv(int matrix_layout, lapack_int n, lapack_int nrhs, float * a, lapack_int lda, lapack_int * ipiv, float * b, lapack_int ldb);
該函數計算AX=B的解。簡單來說,當B為單位矩陣時,X即為inv(A)。
輸入:
matrix_layout:矩陣存儲順序,C++中為行優先LAPACK_ROW_MAJOR
n:線性方程的個數,$n\ge 0$
nrhs:矩陣B的列數,$nrhs\ge 0$
a:大小max(1, lda*n),包含n*n的系數矩陣A
b:列優先存儲時,大小max(1, ldb* nrhs);行優先存儲時,大小max(1, ldb*n);包含n* nrhs的矩陣B
lda:矩陣a的leading dimension,$lda\ge \max (1,n)$
ldb:矩陣b的leading dimension;列優先存儲時,$ldb\ge \max (1,n)$;行優先存儲時,$ldb\ge \max (1,nrhs)$
輸出:
a:(具體看說明文檔)可能會被覆蓋
b:(具體看說明文檔)調用此函數時被覆蓋
ippv:(具體看說明文檔)大小最小是max(1, n)
返回值:0成功,其他不成功
This function returns a value info.
If info=0, the execution is successful.
If info = -i, parameter i had an illegal value.
If info = i, ${{U}_{i,i}}$ (computed in double precision for mixed precision subroutines) is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed.
程序:
1 int SCalcInverseMatrix(float* pDst, const float* pSrc, int dim) 2 { 3 int nRetVal = 0; 4 if (pSrc == pDst) 5 { 6 return -1; 7 } 8 9 int* ipiv = new int[dim * dim]; 10 float* pSrcBak = new float[dim * dim]; // LAPACKE_sgesv會覆蓋A矩陣,因而將pSrc備份 11 memcpy(pSrcBak, pSrc, sizeof(float)* dim * dim); 12 13 memset(pDst, 0, sizeof(float)* dim * dim); 14 for (int i = 0; i < dim; ++i) 15 { 16 // LAPACKE_sgesv函數計算AX=B,當B為單位矩陣時,X為inv(A) 17 pDst[i*(dim + 1)] = 1.0f; 18 } 19 20 // 調用LAPACKE_sgesv后,會將inv(A)覆蓋到X(即pDst)中 21 nRetVal = LAPACKE_sgesv(LAPACK_ROW_MAJOR, dim, dim, pSrcBak, dim, ipiv, pDst, dim); 22 23 delete[] ipiv; 24 ipiv = nullptr; 25 26 delete[] pSrcBak; 27 pSrcBak = nullptr; 28 29 return nRetVal; 30 }
調用:
1 const int nDim = 3; 2 float pa[nDim * nDim] = { 1, 2, 3, 6, 5, 4, 7 ,5 ,8 }; 3 float pb[nDim * nDim]; 4 5 int nRetVal = SCalcInverseMatrix(pb, pa, nDim);
結果:

matlab調用inv后的結果:

可見在精度允許的范圍內,結果一致。
另一方面,在調用LAPACKE_sgesv之前:

調用LAPACKE_sgesv之后:

可見,存儲A的緩沖區被覆蓋。
