Eigen class to take mean of each row of matrix (compute Centroid of the column vectors)

天涯浪子 提交于 2019-12-10 17:53:28

问题


I am really new with C++ but here is what I am trying to do. I have a 4 by 3 matrix:

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

I want to take calculate the mean of each row and store it in some vector. I am using the Eigen library. I cannot think of anything to do this efficiently. Here is my code thus far:

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

So what I have is a 4 by 3 matrix SS and now I want to take the mean of each row and store it in the vector S_A. I having a lot of difficulty with this, so any suggestions would be greatly appreciated.


回答1:


You want a partial reduction:

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



回答2:


Found this which makes it really simple:

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



回答3:


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


来源:https://stackoverflow.com/questions/43196545/eigen-class-to-take-mean-of-each-row-of-matrix-compute-centroid-of-the-column-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!