QT / C++ / Eigen 自己实现的MATLAB中的std()函数,矩阵按照列求标准差
//定义一个按列求标准差的函数,其中A为被求列标准差的矩阵,OutputMatrix为求出的列标准差
void Std(MatrixXd &A, MatrixXd &OutputMatrix)
{
//按列求标准差
int Rows = A.rows();
int Cols = A.cols();
//按列求平均值
MatrixXd A_ColsMean(1,Cols);
A_ColsMean = A.colwise().mean();
//cout << "A_ColsMean:" << endl << A_ColsMean << endl;
//矩阵中每一列的值减去其对应的列平均值
MatrixXd A_std1(Rows,Cols);
for(int i = 0;i < Rows; i++)
{
for(int j = 0;j < Cols; j++)
{
A_std1(i,j) = abs(pow((A(i,j) - A_ColsMean(0,j)),2));
}
}
//cout << "A_std1:" << endl << A_std1 << endl;
MatrixXd A_std2(1,Cols);
A_std2 = A_std1.colwise().sum();
//cout << "A_std2:" << endl << A_std2 << endl;
MatrixXd A_std3(1,Cols);
int n_std;
if(Rows > Cols)
{
n_std = Rows - Cols - 1;
for(int i = 0;i < Cols; i++)
{
A_std3(0,i) = A_std2(0,i) / (Cols + n_std);//
}
}
else if(Rows < Cols)
{
n_std = Cols - Rows + 1;
for(int i = 0;i < Cols; i++)
{
A_std3(0,i) = A_std2(0,i) / (Cols - n_std);//
}
}
else if(Rows = Cols)
{
n_std = 1;
for(int i = 0;i < Cols; i++)
{
A_std3(0,i) = A_std2(0,i) / (Cols - n_std);//
}
}
//qDebug() << "n_std:" << n_std;
MatrixXd A_std(1,Cols);
for(int i = 0;i < Cols; i++)
{
A_std(0,i) = sqrt(A_std3(0,i));
}
//cout << "A_std:" << endl << A_std << endl;
OutputMatrix = A_std;
}
``