特征类取每行矩阵的平均值(计算列向量的质心)

时间:2017-04-04 00:45:47

标签: c++ eigen

我是C ++的新手,但这就是我想做的事情。我有一个4乘3的矩阵:

100 109.523 119.096
100 89.7169  76.256
100 96.0822 103.246
100 101.084 85.0639

我想计算每行的平均值并将其存储在某个向量中。我正在使用Eigen库。我无法想到有效地做到这一点。这是我到目前为止的代码:

MatrixXd SS(N,n+1);
    MatrixXd Z = generateGaussianNoise(N,n);
    for(int i = 0; i < N; i++){
        SS(i,0) = S0;
        for(int j = 1; j <= n; j++){
                SS(i,j) = SS(i,j-1)*exp((double) (r - pow(sigma,2.0))*dt + sigma*sqrt(dt)*(double)Z(i,j-1));
        }
    }

    cout << SS << endl;
    cout << endl;
    VectorXd S_A(3);
    S_A = SS.row(1);

所以我所拥有的是一个4乘3矩阵SS,现在我想取每行的均值并将其存储在向量S_A中。我对此有很多困难,所以任何建议都会非常感激。

3 个答案:

答案 0 :(得分:9)

你想要部分减少:

Vector3d S_A = SS.rowwise().mean();

答案 1 :(得分:0)

发现这一点非常简单:

Map<RowVectorXd> S_temp(SS.data(), SS.size());

答案 2 :(得分:0)

std::vector《double》S_A
double sum(0);
//Loop over SS by row:
for (size_t i=0; nRows < SS.rows(); ++i{
    //clear sum to start over for a given row...
    sum=0;
    //sum all in a row...
    for (size_t j=0; nCols < SS.cols(); ++j){
        //increase some by matrix entry...
        sum+=SS(i,j);
    }
   //Push average on vector by dividing sum by number of cols.  Cast columns to double to divide properly, I think
   S_A.push (sum/(double)SS.cols())
}
//S_A has 'row' entries where each is an average a row...