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_finitereturns a vector of typearma::uvec, which is a typedef forarma::Col<uword>. Every objectColhas an attribute.n_elemwhich 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_elemto tell us the amount of elements it has.Also, if you want to use
accu()you can assign the resulting vector fromfind_finite()to auveclet'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.