while working with the library Armadillo I figured out that there is a recurrent pattern when dealing with missing values. If, for example I want to perform the var
operation on rows of a matrix and handle missing values I will proceed like this
void varianceRows(const mat& M,vec& v)
{
for(uint i=0;i<M.n_rows;i++) // variance calculated on rows
{
if(M.row(i).is_finite())
v(i) = var(M.row(i));
else if(!any(M.row(i)>0))
v(i) = NAN;
else
{
vec b=M.row(i);
v(i) = var(b.elem(find_finite(b)));
}
}
}
Now I realised that it is often the case to perform the same procedure but with different functions (e.g. mean
, median
, sum
etc.). I was then wondering how I can write a generic version of this function so that it can accept different functions as parameters. My attempt for now is:
template<typename Func>
void FuncOnMat(const mat& M,vec& v,Func func)
{
for(uint i=0;i<M.n_rows;i++) // operation calculated on rows
{
if(M.row(i).is_finite())
v(i) = func(M.row(i));
else if(!any(M.row(i)>0))
v(i) = NAN;
else
{
vec b=M.row(i);
v(i) = func(b.elem(find_finite(b)));
}
}
}
but when I execute
FuncOnMat(A,r,mean);
it does not work. I have the feeling I need to feed a functor or a lambda
. Which is the best way to proceed?