Reputation: 3
I have a matrix A and a vector b, I want to solve the linear system Ax = b for x. The problem is that frequently A will be singular. I used RcppArmadillo package in R to do this. Basically I do
arma::mat A = something;
arma::vec b = something;
arma::mat tmp_pinv = arma::pinv(X, 0.001);
arma::mat tmp_res = tmp_pinv * b;
However, I got error message "pinv(): svd failed". Is there any way to solve this? Either I can maybe use different package? Or I can try catch this error and let the problem keeps going? Any thoughts?
Upvotes: 0
Views: 342
Reputation: 1615
If the solution can be approximate, one approach is to iteratively add a small scalar to the diagonal of A to make the matrix non-singular and keep retrying to find the solution.
The solve() function is generally more robust and efficient than pinv() for solving linear systems.
arma::mat A = something;
arma::vec b = something;
arma::mat tmp_res;
bool done = arma::solve(tmp_res,A,b);
int iter = 0;
while(!done) {
A.diag() += 100.0 * arma::datum::eps;
done = arma::solve(tmp_res,A,b);
if(iter > 1000) break; // give up when maximum number of iterations is reached
iter++;
}
Upvotes: 0