Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column wise initialization and calculation of standard deviation in eigen library

Tags:

c++

matlab

eigen3

I did a MATLAB code and I am trying to do it in C++ using Eigen library.In my MATLAB code I had to do a particular function like this

M=10;
s1 = zeros(20,M);
for i=1:M
  s1(:,i) = i*i;%some function 
  s1(:,i) = s1(:,i)/std(s1(:,i));
end

I am confused on using .colwise() and is there an in built function to get standard deviation using Eigen library?

like image 530
Ema Avatar asked Mar 10 '18 08:03

Ema


1 Answers

As Yuyao pointed out, there is no standard deviation function built into Eigen (at the moment). You can compute this for a single vector using the following (generally, prefer using Array if you are working more on element-wise operations):

Eigen::ArrayXd vec;
double std_dev = std::sqrt((vec - vec.mean()).square().sum()/(vec.size()-1));

(Since there was an edit request: Note that for an un-biased estimation of the standard deviation you need to divide by vec.size()-1: [1])

If you want to compute the column-wise std-dev of a whole array, the following should work:

Eigen::Index N = 20, M = 10;
Eigen::ArrayXd angles = Eigen::ArrayXd::LinSpaced(N, -M_PI/2, M_PI/2);

Eigen::ArrayXXd s1(N, M);
for(Eigen::Index i=0; i< s1.cols(); ++i)
{
    s1.col(i) = (i+1)*sin(angles+i);
}

Eigen::Array<double, 1, Eigen::Dynamic> std_dev = ((s1.rowwise() - s1.colwise().mean()).square().colwise().sum()/(M-1)).sqrt();
std::cout << std_dev << "\n\n";

s1.rowwise() /= std_dev;

std::cout << s1 << "\n\n";
like image 55
chtz Avatar answered Nov 15 '22 09:11

chtz