Skip to content

Instantly share code, notes, and snippets.

@ialhashim
Created July 27, 2014 21:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ialhashim/14db82926cdab2575508 to your computer and use it in GitHub Desktop.
Save ialhashim/14db82926cdab2575508 to your computer and use it in GitHub Desktop.
Eigen matrix helper functions - from and to std::vector and from and to file (Qt)
template<typename Scalar, typename Container>
inline static Eigen::Matrix<Scalar,-1,-1> toEigenMatrix( const Container& vectors ){
typedef typename Container::value_type VectorType;
typedef typename VectorType::value_type Scalar;
Eigen::Matrix<Scalar,-1,-1> M(vectors.size(), vectors.front().size());
for(size_t i = 0; i < vectors.size(); i++)
for(size_t j = 0; j < vectors.front().size(); j++)
M(i,j) = vectors[i][j];
return M;
}
template<typename Scalar, typename Matrix>
inline static std::vector< std::vector<Scalar> > fromEigenMatrix( const Matrix & M ){
std::vector< std::vector<Scalar> > m;
m.resize(M.rows(), std::vector<Scalar>(M.cols(), 0));
for(size_t i = 0; i < m.size(); i++)
for(size_t j = 0; j < m.front().size(); j++)
m[i][j] = M(i,j);
return m;
}
// Input / output Eigen matrix from / to disk
#include <QFileInfo>
#include <QTextStream>
static inline Eigen::MatrixXd matrixFromFile( QString filename, QString splitChar = "," )
{
Eigen::MatrixXd M;
// Read data
QFile file( filename );
if(!file.open(QFile::ReadOnly | QFile::Text)) return M;
std::vector< std::vector<double> > mat;
QTextStream in(&file);
QStringList lines = in.readAll().split('\n');
for( auto line : lines ){
auto row_string = line.split(splitChar, QString::SkipEmptyParts);
if(row_string.size() < 1) continue;
std::vector<double> row;
for(auto token : row_string)
row.push_back(token.toDouble());
mat.push_back( row );
}
// Copy values
M = Eigen::MatrixXd(mat.size(), mat.front().size());
for(size_t i = 0; i < mat.size(); i++){
for(size_t j = 0; j < mat.front().size(); j++){
M(i,j) = mat[i][j];
}
}
return M;
}
static inline void matrixToFile(const Eigen::MatrixXd & M, QString filename){
QFile file( filename );
if(!file.open(QFile::WriteOnly | QFile::Text)) return;
QTextStream out(&file);
for(unsigned int i = 0; i < M.rows(); i++)
{
QStringList row;
for(unsigned int j = 0; j < M.cols(); j++)
row << QString::number(M(i,j));
out << (row.join(",") + "\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment