Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an Armadillo function to NOT print an error when inverting a singular matrix?

A buddy and I are working on an R package and using the RcppArmadillo package for some of the heavier matrix algebra. It's going pretty sweet so far but we're having a little issue concerning matrix inversion. Long story short, a program is searching for a particular type of matrix and must check if the updated matrix's inverse exists at each iteration of a loop (the inverse itself is also needed). Right now we're using the function inv(A, B) which returns a boolean indicating if matrix B was invertible or not (if not, A is set to the 0x0 matrix and otherwise A = inv(B)). It would be nice for us if this function didn't print an error because the returned boolean gives the loop the info needed to properly proceed. And it seems like an error is just printed and not "thrown" as the following program shows:

#include <iostream>
#include <armadillo>

using namespace std;
using namespace arma;

int main(int argc, char** argv)
{
    mat A = randu<mat>(5,5);
    mat B = zeros<mat>(5,5);

    inv(A, B);

    cout << A << "error printed but not fatal" << endl;

    A = inv(B);

    cout << A << "never make it this far" << endl;

    return 0;
}

resulting in:

Johns-MacBook-Pro:test johnsherrill$ g++ armaExample.cpp -o example -O2 -larmadillo
Johns-MacBook-Pro:test johnsherrill$ ./example

error: inv(): matrix appears to be singular

[matrix size: 0x0]
error printed but not fatal

error: inv(): matrix appears to be singular

terminate called after throwing an instance of 'std::runtime_error'
  what():  inv(): matrix appears to be singular
Abort trap: 6

Is there a way to get around this without first separately checking if B is invertible? This type of error is printed in R as well.

like image 472
joncheryl Avatar asked Feb 10 '23 17:02

joncheryl


1 Answers

The easiest way is to define ARMA_DONT_PRINT_ERRORS before including the Armadillo header.

For example:

#define ARMA_DONT_PRINT_ERRORS
#include <armadillo>   // or #include <RcppArmadillo.h> if you're using Rcpp

The defines are described in http://arma.sourceforge.net/docs.html#config_hpp

like image 59
mtall Avatar answered Feb 13 '23 05:02

mtall