This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Tips on matlab .mat file interop?

Tags: None
(comma "," separated)
EamonNerbonne
Registered Member
Posts
36
Karma
0

Tips on matlab .mat file interop?

Tue Dec 15, 2009 2:22 pm
I'm hoping to easily read/write data files in matlab's .mat file format. Does anyone know of a simple means to do so?
I don't need any particularly complex matlab features; the ability to load a .mat file and extract/write the value of a few stored matrices would be sufficient.

Since I'm using eigen for most of my matrix needs, clean interop with eigen would be a boon - but really, anything that makes writing/reading floating point matrices to/from a .mat file would work for me. I'm hoping others have needed to do this before and done all the hard work for me, naturally ;-).

Anyone have any tips?
RENOO
Registered Member
Posts
21
Karma
0
OS

Re: Tips on matlab .mat file interop?

Tue Dec 15, 2009 10:15 pm
Hi,
I am not sure this is a good forum to post on propriatery software such as Matlab.
Anyway if you mean do read and write .mat files Without the matlab software, octave should do the job.
User avatar
Alec
Registered Member
Posts
565
Karma
1
OS

Re: Tips on matlab .mat file interop?

Wed Dec 16, 2009 12:57 am
Not sure if it would helps, but after a quick search, I found yacc/lex files for the Matlab grammar on this page, so if you end up writing a parser, it might help.


Get problems solved faster - get reply notifications through Jabber!
Hauke
Registered Member
Posts
109
Karma
3
OS
Hi,

given you have Matlab installed you are probably looking for the commands

Code: Select all
MATFile *matOpen(const char *filename, const char *mode);
int matClose(MATFile *mfp);

int matPutVariable(MATFile *mfp, const char *name, const mxArray *pm);
mxArray *matGetVariable(MATFile *mfp, const char *name);


Those are all defined in "mat.h".

To create an mxArray the following code should work (I think it requires "matrix.h")

Code: Select all
    template <typename Derived>
    mxArray* cvt2mxArray(const Eigen::MatrixBase<Derived>& data)
    {
      const int rows = data.rows();
      const int cols = data.cols();
      mxArray* mx_data = mxCreateDoubleMatrix(rows, cols, mxREAL);
      for (int row_idx = 0; row_idx < rows; ++row_idx)
      {
        for (int col_idx = 0; col_idx < cols; ++col_idx)
        {
          mxSetScalar(mx_data, row_idx, col_idx, data(row_idx,col_idx));
        }
      }
      return mxArray;
    }


Finally you need to cleanup your data with mxDestroyArray.

I am leaving the conversion from mxArray to Eigen matrices up to you and the fine tuning for the proper Scalar support too...

Cheers,
Hauke


Bookmarks



Who is online

Registered users: Bing [Bot], daret, Google [Bot], sandyvee, Sogou [Bot]