Number of finite elements

244 views Asked by At

I'm attempting to find the number of finite elements in a matrix in C++ using Armadillo. Assuming a double matrix y, I would think I could do so with (inside a mex function)

mexPrintf("finite_y: %g\n", (double) accu(find_finite(y)));

But this returns

[Matlab] finite_y: 1.41381e+09

However, I can get it to work with

mat y_ones = mat(y.n_rows, y.n_cols, fill::ones);
mexPrintf("finite_y (sum-ones): %g\n", accu(y_ones(find_finite(y))));

[Matlab] finite_y (sum-ones): 53150

How can I use accu with find_finite to get the number of finite elements in a matrix without creating a matrix of ones?

1

There are 1 answers

0
Ediac On BEST ANSWER

find_finite returns a vector of type arma::uvec, which is a typedef for arma::Col<uword>. Every object Col has an attribute .n_elem which indicates the vector's length. Because find_finite() returns a vector that contains the indices of elements of X(argument) that are finite, one can simply assign that vector to a variable of type arma::uvec, or construct a copy of the resulting vector, and call its attribute .n_elem to tell us the amount of elements it has.

Also, if you want to use accu() you can assign the resulting vector from find_finite() to a uvec let's call it for example arma::uvec newvector;, then use its member function newvector.ones() which will set all its elements to 1. Then use accu(newvector), which is similar to what you did.

Disclaimer: I've previously used Armadillo some time ago, might be outdated.