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?
find_finite
returns a vector of typearma::uvec
, which is a typedef forarma::Col<uword>
. Every objectCol
has an attribute.n_elem
which indicates the vector's length. Becausefind_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 typearma::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 fromfind_finite()
to auvec
let's call it for examplearma::uvec newvector;
, then use its member functionnewvector.ones()
which will set all its elements to 1. Then useaccu(newvector)
, which is similar to what you did.Disclaimer: I've previously used Armadillo some time ago, might be outdated.