Home

Awesome

eigen-matio (MATio)

C++11 single-file-header MATio for reading and writing Eigen matrices to/from matlab data files. It uses the 'matio' library as a backend.

eigen-mexeig (MexEig)

C++11 single-file-header MexEig for inclusion in mex files to simply convert Eigen matrices to and from mxArray structures.

Overview

There are two functions in MexEig:

MATio exports a single class MatioFile():

And two stand-alone functions that throw standard exceptions on error conditions:

Using (MexEig)

Just #include "MexEig" in a mex .cpp file, and call the wrappers. If the requested conversions are impossible, exceptions will be thrown, so maybe catch those:

#include "mex.h"
#include <iostream>
#include <Eigen/Core>
#include "MexEig"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  try {
    if (nrhs != 1) throw std::invalid_argument("requires one input arg");
    if (nlhs != 1) throw std::invalid_argument("requires one ouput arg");

    Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic> x;
    MxArrayToEigen(x, prhs[0]);
    plhs[0] = EigenToMxArray(x);
  }
  catch (std::exception & ex) {
    mexErrMsgIdAndTxt("tmp:error", ex.what());
  }
}

Using (MATio)

Using the bare functions in MATio:

#include <iostream>
#include "Eigen/Dense"
#include "MATio"

using namespace Eigen;

int main(int argc, char *argv[])
{
  Matrix3f ff;
  
  // read matrix 'ff' from file 'data.mat' in as floats
  try {
    read_mat("data.mat", "ff", ff);
    std::cout << "ff=" << ff << std::endl;
  
    // write it back out as double precision 'dd'
    write_mat("data.mat", "dd", ff.cast<double>());
  }
  catch (const std::exception & ex) {
    std::cout << "error:" << ex.what() << std::endl;
  }
}

Using the MatioFile class, potentially more efficient:

#include "Eigen/Core"
#include "Eigen/Dense"
#include ".../MATio"

using namespace Eigen;
int main(int argc, char *argv[])
{
  MatioFile file("data.mat");
  Matrix3f ff;
  
  // read matrix 'ff' in as single precision
  if (!file.read_mat("ff", ff)) {
    // show what we got
    std::cout << "ff=" << ff << std::endl;
  }
  else {
    std::cout << "error: " << file.lasterr() << std::endl;
  }

  ff = Matrix3f::Random();
  
  // write ff as double precision matrix 'dd'
  if (file.write_mat("dd", ff.cast<double>()))
    std::cout << "error: " << file.lasterr() << std::endl;
}

Building the tests

git clone git@github.com:tesch1/eigen-matio.git
cd eigen-matio
cmake -Bbuild .
cmake --build build
cmake --build build --target test

Octave test

There's a small example showing how to build an octave module using MexEig

Contributing

Contributions / bug fixes welcome. They must be MPL2 licensed and maintain the same code formatting.

TODO

ChangeLog

License

Mozilla 2.0, like the rest of Eigen.