Eigen is a great tool for matrix operations, here I found a small piece of code in Github that enables you to generate multivariate normal distribution samples using C++11 and Eigen library. The below is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
#include <fstream> #include <Eigen/Eigen> #include <Eigen/Core> #include <Eigen/Dense> #include "eigenmvn.h" int main(int argc, char ** argv) { //number of columns const uint n_cols = 2; // number of rows const uint n_rows = 5000; Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> total_gaussian_data_eigen, first_gaussian_data_eigen,second_gaussian_data_eigen; first_gaussian_data_eigen.setZero(n_rows,n_cols); second_gaussian_data_eigen.setZero(n_rows,n_cols); //2*n_rows since we want to concat first and second and put it in this matrix total_gaussian_data_eigen.setZero(2*n_rows,n_cols); Eigen::Vector2f mean; Eigen::Matrix2f covar; float theta; mean << 0,0; // Set the mean /* our covar matrix: |10 0| |0 1| */ covar <<10,0,0,1; //first gaussian Eigen::EigenMultivariateNormal<float> normX_solver1(mean,covar); first_gaussian_data_eigen<< normX_solver1.samples(n_rows).transpose() ; //secodn gaussian mean << 4,4; // Set the mean // Create a covariance matrix rotated clockwise by theta theta=M_PI/4.0; covar=genCovar(1,4,theta); Eigen::EigenMultivariateNormal<float> normX_solver2(mean,covar); second_gaussian_data_eigen<<normX_solver2.samples(n_rows).transpose() ; //concating two gaussians total_gaussian_data_eigen<<first_gaussian_data_eigen,second_gaussian_data_eigen; //writing data into output in csv format std::cout<<"x,y\n"; for (uint i = 0; i < total_gaussian_data_eigen.rows(); i++) { for (uint h = 0; h < n_cols-1; h++) { std::cout<<total_gaussian_data_eigen(i,h); std::cout<<","; } std::cout<<total_gaussian_data_eigen(i,n_cols-1); std::cout<<std::endl; } } |