I wrote the following C code for a project some time ago. It;s a little dated but it worked with matlab 2011a. It should serve as an example if nothing else. It does make a number of assumptions - mostly documented.
Input parameters are the filename to write to, an array of pointers to CvMat, an array of names for these matrices and the number of matrices to write.
void writeMatFile( const char *fileName, CvMat ** matrices, const char **names, int numMatrices ) {
FILE *file = fopen( fileName, "wb" );
for( int i=0; i<numMatrices; i++ ) {
CvMat * mat = matrices[i];
const char *name = names[i];
// If mat is ND we write multiple copies with _n suffixes
int depth = CV_MAT_CN(mat->type);
for( int d=0; d<depth; d++ ) {
// Assumption that we are always dealing with double precision
uint32_t MOPT = 0000;
fwrite(&MOPT, 1, sizeof( uint32_t), file);
uint32_t mrows = mat->rows;
uint32_t ncols = mat->cols;
uint32_t imagef = 0;
char nameBuff[ strlen( name ) + 10];
strcpy(nameBuff, name);
if( depth>1) {
char suffix[5];
sprintf(suffix, "_L%d", d+1);
strcat(nameBuff, suffix);
}
uint32_t nameLength = strlen( nameBuff ) + 1;
fwrite( &mrows, 1, sizeof( uint32_t), file);
fwrite( &ncols, 1, sizeof( uint32_t), file);
fwrite( &imagef, 1, sizeof( uint32_t), file);
fwrite( &nameLength, 1, sizeof( uint32_t), file);
fwrite( nameBuff, nameLength, 1, file );
for( int col = 0; col<ncols; col++ ) {
for( int row=0; row<mrows; row++ ) {
CvScalar sc = cvGet2D(mat, row, col);
fwrite(&(sc.val[d]), 1, sizeof( double ), file);
}
}
}
}
fclose( file );
}