Portable Matlab File Exporter

By Malcolm McLean Homepage

This file provides functions for exporting Matlab format .mat files from C or C++ programs.


Sometimes it is handy to be able to able to export data in Matlab format from a C program, for instance if the data needs to be graphically and statistically analysed in Matlab. The following functions give a very basic capability.

Unfortunately the Matlab format is very elaborate, and it is quite difficult to write a reader that will support all .mat files. However it is easy enough to write a writer. Our writer supports double matrices, ASCII strings, and cells. Since most data is usually either numbers or strings, that should be adequate for most purposes. There are two interfaces, the very simple one if you just want to dump a matrix or a list of strings to a .mat file, and a more complex one for if you want to build up .mat files out of several elements.

int err;
double data[12] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int Nrows = 3; int Ncols = 4;
mf = openmatfile("temp.mat", &err);
   /* err gives the reason for the error */;
matfile_addmatrix(mf, "x", data, Nrows, Ncols, 0);
matfile_addmatrix(mf, "y", data, Ncols, Nrows, 1);
matfile_addstring(mf, "string1", "My name is Fred");
/* error handler here */;

This code create a MATFILE object, writes a matrix to it, writes the same data with rows and columns transposed, and then writes a string. That's all there is to basic Matfile export.

matfile_cellpush(mf, "acell", 10, 1); /* start a cell array */
/* first nine cells are strings */
    matfile_addstring(mf, "a", "Fred");
  matfile_cellpush(mf, "a", 1, 2); /* last element is a cell */
    matfile_addmatrix(mf, "a", data, 10, 10, 0);
    matfile_addstring(mf, "a", "Jim");
matfile_cellpop(mf); /* end the cell array */

Matlab cell arrays can contain elements of different sizes or different types. They can also contain other cell arrays. This leads to a stack-like structure of cell nesting which is best handled by a push() / pop() type interface. Note that you need to know the cell dimensions before pushing. When an object is written to a cell array, the name is ignored, so just pass in a dummy name.

int writematmatrix(char *fname, char *name, double *data, int m, int n, int transpose);
int writematstrings(char *fname, char *name, char **str, int N);

These are the interfaces for the two simple functions. They write a single matrix or single list of strings as a .mat file, in one call. Handy if you just want to dump data to Matlab.

A note on portable IEEE 754 export

Virtually all computers now use the IEEE 754 format for floating point numbers. Matlab uses this format to store doubles internally. However you may be running C on some exotic or legacy hardware where the internal floating point representation is different. Therefore the internal function fwriteieee754() will write floating point value portably, regardless of the internal floating point representation. if execution speed is an issue and you know you are running on IEEE 754 hardware, you can simply repalce this function with a byte-wise copy.



MATFILE *openmatfile(char *fname, int *err)

Opens a new matfile. The MATFILE structure contains the FILE * and some associated data, and should be tereated as opaque. If the function fails it returns null, error codes are 0 = OK, -1 out of memory, -2 error opening file (usually because the path is invalid), -3 IO error (rare, usually a hardware problem of some sort).


int matfile_addmatrix(MATFILE *mf, char *name, double *data, int m, int n, int transpose)

Write a matrix to a mat file. name gives the variable name that Matlab will use to identify the matrix. data is always passed in as a flat array. Matlab internal format is row major, whilst C is internally column-major. The function will convert from C to Matlab unless the transpose flag is set. Return value is -1 on error.


int matfile_addstring(MATFILE *mf, char *name, char *str)

Write a string to a mat file. name gives the Matlab identifer for the string, whilst str gives the string. Internal Matlab uses a 16-bit Unicode representation. This function simply converts ASCII to Unicode, and non-ASCII characters of over 127 may not be translated correctly.


int matfile_cellpush(MATFILE *mf, char *name, int m, int n)

This function starts a cell array. name gives the identifier Matlab uses to identify the cell array. m and n give the cell array dimensions, and must be known. Write elements to the cell array using matfile_addmatrix() or matfile_addstring, using a dummy name. After you have finsihed, call matfile_cellpop. Matlab cell arrays can contain other cell arrays as members. So you can nest calls to matfile_cellpush and matfile_cellpop


int matfile_cellpop(MATFILE *mf)

This function finishes the cell array after you have written all the elements. Internally Matlab stores the cell array size, so the fucntion needs to find the size field, seek to it, and write the amount of data written. fseek() and ftell() are used to do the seeking. This might break on huge data sets if cell arrays go over 32 bits.


int matfile_close(MATFILE *mf)

This fucntion is the equivalent of fclose() on a MATFILE *. Afgter it is called the mat file shiuld be written, and all internal data is released. The MATFILE * becomes invalid. It is quite common to ignore the return from fclose(), which is a bit sloppy. Don't ignore the return from matfile_close(), unless you have no way of recovering from an error, as the MATFILE error state is sticky. It's only necessary to test this one call to determine whether everything was written correctly.


int writematmatrix(char *fname, char *name, double *data, int m, int n, int transpose)

Convenience function to write a single matrix as a .mat file in one go.


int writematstrings(char *fname, char *name, char **str, int N)

Convenience function to write a list of strings to a.mat file as a cell array of strings, in one go.