Skip to content

Instantly share code, notes, and snippets.

@AtsushiSakai
Last active December 18, 2015 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AtsushiSakai/5727632 to your computer and use it in GitHub Desktop.
Save AtsushiSakai/5727632 to your computer and use it in GitHub Desktop.
EigenMatLib.h : C++行列演算ライブラリEigenを使った,MATLABの便利関数を模倣したヘッダライブラリ.
//-------------------------------------------------------------------------
//
// File : EigenMatLib.m
//
// Discription : Eigen Library inspired by Matlab functions.
//
// Environment : C++
//
// Author : Atsushi Sakai
//
// Copyright (c): 2013 Atsushi Sakai
//
// License : Modified BSD Software License Agreement
//-------------------------------------------------------------------------
#ifndef INCLUDED_EIGENMATLIB
#define INCLUDED_EIGENMATLIB
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
// Standard deviation
// input
// X:data vector
// flag: 0 or 1
// dim : 1 or 2
// output
// stdResult: Standar deviation value.
// if an error is detected, empty matrix will resturn.
MatrixXf Std(const MatrixXf& X,int flag,int dim){
MatrixXf stdResult;
if(X.size()==0){//data size check
cout<<"Error Std:Input data is empty."<<endl;
}
if(flag<0||flag>1){//flag check
cout<<"Error Std:flag is imvalid."<<endl;
}
if(dim<1||dim>2){//flag check
cout<<"Error Std:dim is imvalid."<<endl;
}
int ncol=X.cols();
int nrow=X.rows();
if(dim==1){//row-wise
stdResult.resize(1,ncol);
double mean;
for(int i=0;i<ncol;i++){
mean=X.col(i).mean();
stdResult(0,i)=(X.col(i)-MatrixXf::Constant(nrow,1,mean)).squaredNorm();
if(flag==0){
if(nrow>1){
stdResult(0,i)=sqrt(stdResult(0,i)/(nrow-1));
}
else{
stdResult(0,i)=0;
}
}
else{
stdResult(0,i)=sqrt(stdResult(0,i)/nrow);
}
}
}
else{//col-wise
stdResult.resize(nrow,1);
double mean;
for(int i=0;i<nrow;i++){
mean=X.row(i).mean();
stdResult(i,0)=(X.row(i)-MatrixXf::Constant(1,ncol,mean)).squaredNorm();
if(flag==0){
if(ncol>1){
stdResult(i,0)=sqrt(stdResult(i,0)/(ncol-1));
}
else{
stdResult(0,i)=0;
}
}
else{
stdResult(i,0)=sqrt(stdResult(i,0)/ncol);
}
}
}
return stdResult;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment