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

3

6

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.

Release answered 4/4, 2017 at 0:45 Comment(0)
K
23

You want a partial reduction:

Vector3d S_A = SS.rowwise().mean();
Kamacite answered 4/4, 2017 at 8:41 Comment(0)
R
0
std::vector<double> S_A;
double sum = 0;
// Loop over SS by row:
for (size_t i=0; i < SS.rows(); ++i) {
    //clear sum to start over for a given row...
    sum=0;
    //sum all in a row...
    for (size_t j=0; j < 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...
Rigorism answered 4/4, 2017 at 1:25 Comment(0)
R
-2

Found this which makes it really simple:

Map<RowVectorXd> S_temp(SS.data(), SS.size());
Release answered 4/4, 2017 at 1:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.