Mon Feb 25, 2013 9:01 pm
I have read the documentation pages "Writing Functions Taking Eigen Types as Parameters" and "Ref< PlainObjectType, Options, StrideType > Class Template Reference" which describe how to define function parameters to avoid evaluation into temporaries.
Are there any similar details that need to be taken care of when writing functions that return eigen types, not a a pass by reference parameter, but as the return type of the function, for example:
MatrixXf cov(const Ref<const MatrixXf>& x, const Ref<const MatrixXf>& y)
const float num_observations = static_cast<float>(x.rows());
const RowVectorXf x_mean = x.colwise().sum() / num_observations;
const RowVectorXf y_mean = y.colwise().sum() / num_observations;
return (x.rowwise() - x_mean).transpose() * (y.rowwise() - y_mean) / num_observations;
MatrixXf C = cov(a,b) + cov(c,d)
Are cov(a,b) and cov(c,d) evaluated into temporaries and if so what is the recommended procedure to avoid this?
Tue Feb 26, 2013 7:03 am
cov(a,b) and cov(c,d) are evaluated into temporaries because the function returns an actual object (vs. a template expression) by value.
Overcoming this problem is quite difficult. A potential solution might be C++11's trailing return types.
Keep in mind that oftentimes, as for instance in this example, you actually want a temporary. Just consider for a moment, how costly it would be to access a single coefficient of an expression cov(x,y) and how many operations you would be performing redundantly (e.g. the de-meaning) during each access...
Registered users: Baidu [Spider], Bing [Bot], davidemme, Exabot [Bot], Google [Bot], Sogou [Bot], Yahoo [Bot]