获取 Eigen::vector 的标准差

Getting the standard deviation of a Eigen::vector

我需要 Eigen 库中向量的标准偏差。我还没有找到它。所以我试了一下:

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())

但是出现错误。

错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0349   no operator "-" matches these operands  

一个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.

因此,将您的 Eigen::Matrix ys 转换为 Eigen::Array 就足以让您的公式生效:

double const std_dev = sqrt((ys.array() - ys.mean()).square().sum() / (ys.size() - 1));