我正在尝试实现矩阵的伪逆计算A *,以解决C ++中具有尺寸的正方形nxn矩阵A的Ax = b的问题。 A *的算术公式是通过SVD分解得出的。
所以首先我计算SVD(A)= USV ^ T,然后 A * = VS U ^ T,其中S 是反对角线S,其中非零元素si在S *中变为1 / si。最后,我计算出解x = A * b
但是我没有得到正确的结果。我正在使用LAPACKE接口进行c ++和cblas进行矩阵乘法。这是我的代码:
ChatBubble chatBubble = getItem(position);
在第二个cblas_dgemm之后,预期在r2中具有A *伪逆。但是,与matlab pinv比较后,我没有得到相同的结果。如果我打印r2,结果为:
double a[n * n] = {2, -1, 2,1};
double b[n]={3,4};
double u[n * n], s[n],vt[n * n];
int lda = n, ldu = n, ldvt = n;
int info = LAPACKE_dgesdd(LAPACK_COL_MAJOR, 'A', n, n, a, lda, s,
u, ldu, vt, ldvt);
for (int i = 0; i < n; i++) {
s[i] = 1.0 / s[i];
}
const int a = 1;
const int c = 0;
double r1[n];
double r2[n];
double res[n];
//compute the first multiplication s*u^T
cblas_dgemm( CblasColMajor,CblasNoTrans, CblasTrans, n, n, n, a, u, ldvt, s, ldu, c, r1, n);
//compute the second multiplication v^T^T=vs*u^T
cblas_dgemm( CblasColMajor,CblasTrans, CblasNoTrans, n, n, n, a, vt, ldvt, r1, ldu, c, r2, n);
//now that we have the pseudoinverse A* solve by multiplying with b.
cblas_dgemm( CblasColMajor,CblasNoTrans, CblasNoTrans, n, 1, n, a, r2, ldvt, b, ldu, c, res, n);
但应该是
0.25 0.50
0.25 0.50
答案 0 :(得分:0)
LAPACKE_dgesdd()
的参数S
表示SVD decomposition中矩阵的奇异值。尽管长度为n
,但它没有描述矢量,因为它表示对角矩阵。确实,Su ^ T的结果是大小为n*n
的矩阵。
例程cblas_dscal()
可以在循环中应用,以计算涉及对角矩阵的矩阵乘积,尽管生成的S.u ^ t仍然是转置的。参见what is the best way to multiply a diagonal matrix in fortran
以下代码可以由g++ main.cpp -o main -llapacke -llapack -lgslcblas -lblas -lm -Wall
(或-lcblas` ...)编译。
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
extern "C" {
#include <lapacke.h>
#include <cblas.h>
}
int main(int argc, char *argv[])
{
const int n=2;
double a[n * n] = {2, -1, 2,1};
double b[n]={3,4};
double u[n * n], s[n],vt[n * n];
int lda = n, ldu = n, ldvt = n;
//computing the SVD
int info = LAPACKE_dgesdd(LAPACK_COL_MAJOR, 'A', n, n, a, lda, s,
u, ldu, vt, ldvt);
if (info !=0){
std::cerr<<"Lapack error occured in dgesdd. error code :"<<info<<std::endl;
}
for (int i = 0; i < n; i++) {
s[i] = 1.0 / s[i];
}
const int aa = 1;
const int c = 0;
//double r1[n*n];
double r2[n*n];
double res[n];
//compute the first multiplication s*u^T
// here : s is not a vector : it is a diagonal matrix. The ouput must be of size n*n
//cblas_dgemm( CblasColMajor,CblasNoTrans, CblasTrans, n, n, n, aa, u, ldvt, s, ldu, c, r1, n);
for (int i = 0; i < n; i++) {
cblas_dscal(n,s[i],&u[i*n],1);
}
//compute the second multiplication v^T^T=vs*u^T
cblas_dgemm( CblasColMajor,CblasTrans, CblasTrans, n, n, n, aa, vt, ldvt, u, ldu, c, r2, n);
//now, r2 is the pseudoinverse of a.
//now that we have the pseudoinverse A* solve by multiplying with b.
cblas_dgemm( CblasColMajor,CblasNoTrans, CblasNoTrans, n, 1, n, aa, r2, ldvt, b, ldu, c, res, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout<<r2[i*n+j]<<" ";
}
}
std::cout<<std::endl;
}
它将显示预期结果:
0.25 0.25 -0.5 0.5