July 2, 2012

Writing Matlab files from C

Normally I'm not a fan of closed tools and even less a fan of closed file formats, but lately I've been struggling with some numerical code and the FOSS tools haven't been working well enough (which is a topic for another day). Simply put, I need something that does matrix arithmetic correctly and that is easy to manipulate/debug data structures in. I could use SciPy, but I've never liked Python and Matlab makes what I need trivial. Since gfortran and ifort both seem to generate incorrect debug symbols on the code I'm working with, and Matlab's text->double parser seems buggy I've been looking for a solution to get my data (correctly!) into Matlab. Matlab/Mathworks does provide an API for this, but using it would require me to have at least most of a Matlab install on all the machines I'm running on - not feasible. Luckily, an open source solution for writing .mat files does exist: MatIO. I found a wiki that claims to document how to use it, but their examples don't seem to work with the current version (they compile and run, but the output isn't right). Based on the wiki and “test_mat.c” included with the MatIO distribution, I was able to get this minimal example working on OSX Lion:

 #include <matio.h> 
 int main(int argc, char** argv) { 
 double a[5] = {1.0,2.0,3.0,4.0,5.0};
 mat_t* mat;
 matvar_t* matvar;
 size_t dims[2] = {1,5};
 mat = Mat_CreateVer("test.mat", NULL, MAT_FT_DEFAULT);
 matvar = Mat_VarCreate("vector", MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims,a,0);
 Mat_VarWrite(mat, matvar, MAT_COMPRESSION_NONE);
 Mat_VarFree(matvar);
 Mat_Close(mat);
 return(0);
 }
I'm compiling this as follows (though you could probably use gcc or icc if you wanted)
 clang -g -Wall -L../1.5.0/lib -I../1.5.0/include/ vector.c -lmatio -lm -lz 

(where my MatIO install is in ../1.5.0 and my test code is called “vector.c”) This is all I really need, but the library can write a few different formats and various data types (apparently a few recent versions of Matlab even use HDF5 rather than a closed format!)

Powered by Hugo & Kiss.