I am trying to implement the pseudoinverse computation A* of a matrix in order to solve the Ax=b for a square nxn matrix A with dimensions in C++. The arithmetic formula for A* is through the SVD decomposition.
So first I compute SVD(A)=USV^T and then A*=VSU^T, where S is the inverse diagonal S where its non-zero element si becomes 1/si in S*. Finally i compute the solution x=A*b
However I am not getting the correct result. I am using LAPACKE interface for c++ and cblas for matrix multiplication. Here is my code:
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);
after the second cblas_dgemm it is expected to have A* the pseudoinverse in r2. However after comparing with matlab pinv I am not getting the same result. If I print r2 the result gives:
0.25 0.50
0.25 0.50
but it should be
0.25 -0.50
0.25 0.50