Skip to content

Instantly share code, notes, and snippets.

@tesch1
Last active October 22, 2018 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tesch1/50fa836e72153113fe56b14a61c8a4b6 to your computer and use it in GitHub Desktop.
Save tesch1/50fa836e72153113fe56b14a61c8a4b6 to your computer and use it in GitHub Desktop.
ouput Eigen matrices in matlab / octave compatible format
/*
* this stuff can go in a header to make std::complex<> available
*/
/* compile:
clang++ -std=c++11 test3.cpp -I eigen/ -DEIGEN_TOO
*/
typedef double real_t;
#include <iostream>
#include <complex>
template <typename Tp>
struct cxwrap : public std::complex<Tp> {
typedef std::complex<Tp> base_t;
using base_t::base_t;
cxwrap<Tp>(const base_t & cx) : base_t(cx) {}
operator base_t() { return *this; }
using base_t::operator+=;
using base_t::operator-=;
using base_t::operator*=;
using base_t::operator/=;
using base_t::operator=;
using base_t::real;
using base_t::imag;
template <class T, class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const cxwrap<T>& x);
};
#ifdef EIGEN_TOO
#include <Eigen/Dense>
namespace Eigen {
template<typename _Real> struct NumTraits<cxwrap<_Real> >
: NumTraits<std::complex<_Real> > {};
}
typedef cxwrap<real_t> complext;
#endif
/*
* below here can go in a .cpp file
*/
template <class T, class CharT, class Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& o,
const cxwrap<T>& x)
{
std::basic_ostringstream<CharT, Traits> s;
s.flags(o.flags());
s.imbue(o.getloc());
s.precision(o.precision());
s << x.real() << std::showpos << x.imag() << "i";
return o << s.str();
}
#include <Eigen/Dense>
//using namespace std::literals::complex_literals;
int main(int argc, char * argv[])
{
Eigen::Matrix<complext, 3,3> x;
Eigen::IOFormat NormalFmt;
Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, ", ", ";\n", "", "", "[", "]");
complext y = std::complex<double>(1,2);
//y = 1.0 + 1i;
//srand((unsigned int) time(0));
x.setRandom();
std::cout << sinh(y) << "\n";
std::cout << "------------------------\n";
std::cout << x << "\n";
std::cout << "------------------------\n";
std::cout << (x+x).format(NormalFmt) << "\n";
std::cout << "------------------------\n";
std::cout << (x*x).format(OctaveFmt) << "\n";
std::cout << "------------------------\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment