I need to have standard deviation of a vector in Eigen library. I have not found it. So i tried it:
Eigen::VectorXd ys(5);
ys << 1, 2, 3, 4, 5;
double std_dev = sqrt((ys - ys.mean()).square().sum() / (ys.size() - 1)); // Error with minus sign (ys-ys.mean())
But getting error.
error:
Severity Code Description Project File Line Suppression State
Error (active) E0349 no operator "-" matches these operands
An Eigen::VectorXd
is defined as typedef Matrix<double, Dynamic, 1> VectorXd;
so it is a special form of an Eigen::Matrix
. You are trying to subtract a scalar ys.mean()
from a vector ys
which is an coefficient-wise operation. The Eigen::Matrix
class is not intended to be used with coefficient-wise operations but for linear algebra. For performing coefficient-wise operations Eigen has the Eigen::Array
class.
Therefore it is sufficient to convert your Eigen::Matrix
ys
to an Eigen::Array
for your formula to work:
double const std_dev = sqrt((ys.array() - ys.mean()).square().sum() / (ys.size() - 1));