Announce

PukiWiki contents have been moved into SONOTS Plugin (20070703)

Matlab C Library Mat File Operations

Table of Contents

Matlab C Library Mat File Operations

#include <mat.h>
matClose (C and Fortran)	Close MAT-file
matDeleteVariable (C and Fortran)	Delete named mxArray from MAT-file
MATFile (C and Fortran)	Type for a MAT-file
matGetDir (C and Fortran)	Get directory of mxArrays in MAT-file
matGetFp (C)	Get file pointer to MAT-file
matGetNextVariable (C and Fortran)	Read next mxArray from MAT-file
matGetNextVariableInfo (C and Fortran)	Load array header information only
matGetVariable (C and Fortran)	Read mxArray from MAT-files
matGetVariableInfo (C and Fortran)	Load array header information only
matOpen (C and Fortran)	Open MAT-file
matPutVariable (C and Fortran)	Write mxArrays to MAT-files
matPutVariableAsGlobal (C and Fortran)

Examples

Load a .mat file

MATFile *matFILE;
const char filename[] = "test.mat";
const char* varname;
mxArray *X;
// open mat file and read it's content
if( (matFILE = matOpen(filename, "r" )) == NULL )
    printf("Error Opening File: \"%s\"\n", argv[1]);
    return;
}
	
/* Read in each array. */
X = matGetNextVariable(matFILE, &varname);
while(X != NULL) {
    printf("Variable name = %s\n", varname);
    // print matrix
    mlfPrintMatrix(X);
    //destroy allocated matrix
    mxDestroyArray(X);
    // get the next variable
    X = matGetNextVariable(matFILE, &varname);
}
matClose(matFILE);
    MATFile *matFILE = matOpen("filename.mat", "r" );
    if( matFILE == NULL ) return;
    mxArray *VQ      = matGetVariable(matFILE, "VQ");
    mxArray *V       = matGetVariable(matFILE, "V");
    mxArray *Me      = matGetVariable(matFILE, "Me");
    mxArray *Lambda  = matGetVariable(matFILE, "Lambda");
    mxArray *TP      = matGetVariable(matFILE, "TP");
    mxArray *P       = matGetVariable(matFILE, "P");
    mxArray *sqsigma = matGetVariable(matFILE, "sqsigma");
    mxArray *Mu      = matGetVariable(matFILE, "Mu");
    mxArray *VQ      = matGetVariable(matFILE, "VQ");
    matClose(matFILE);

Write a .mat file

MATFile *matFILE;
const char* varname;
mxArray *X;
// open mat file and read it's content
if( (matFILE = matOpen("test.mat", "r" )) == NULL )
    printf("Error Opening File: \"%s\"\n", argv[1]);
    return;
}

// data creation
double data1[] = {1.0, 2.0, 3.0, 4.0, 5.0};
double data2[] = {1, 2, 3};
mxArray *X, *Y;

X = mxCreateDoubleMatrix(1, 5, mxREAL);
Y = mxCreateDoubleMatrix(1, 3, mxREAL);

//copy an array to matrix A and B
memcpy(mxGetPr(X), data1, 5 * sizeof(double));
memcpy(mxGetPr(Y), data2, 3 * sizeof(double));

// open mat file to write
matFILE = matOpen("test.mat", "w");
matPutVariable(matFILE, "X", X);
matPutVariable(matFILE, "Y", Y);
matClose(matFILE);
	
mxDestroyArray(X);
mxDestroyArray(Y);

References