iceman
iceman

Reputation: 4261

Use Matlab cell array in a C/C++ program

How can I read a Matlab cell array stored as a .mat file and having 3*3*2 multidimensional double data into a c/c++ array ?

Upvotes: 4

Views: 4569

Answers (3)

user244795
user244795

Reputation: 708

Link against libmx.lib, libmat.lib, libeng.lib, and include the headers mat.h and engine.h. I'm ignoring the imaginary component of the data and assuming you know how to use the C++ STL. The code below is adequate, but an easier interface called mxWrapper is available here: http://www.mathworks.com/matlabcentral/fileexchange/28331-replacement-for-mwarray-using-matlab-engine

vector<double> readSomeNumbers() {

    vector<double> data;

    mxArray *pMx=load("c:\\someFile.mat", "foobar");

    if (!pMx) return data;

    ASSERT(mxGetClassID(pMx) == mxDOUBLE_CLASS);

    data.assign(mxGetPr(pMx), mxGetPr(pMx)+mxGetNumberOfElements(pMx));

    mxDestroyArray(pMx);

    return data;
}

mxArray *load(const string& fileName, const string& variableName)
{

    MATFile *pmatFile = matOpen(fileName.c_str(), "r");

    if(pmatFile == NULL) 
        return NULL;

    mxArray* pMx = matGetVariable(pmatFile, variableName.c_str());

    if(pMx == NULL) 
    {
        matClose(pmatFile);
        return NULL;
    }

    matClose(pmatFile);
    return pMx;
}

Upvotes: 2

P-Nuts
P-Nuts

Reputation: 899

The MATLAB file format is documented here. Doesn't look too hairy.

Edit: Sorry, the link got corrupted.

Upvotes: 1

yuk
yuk

Reputation: 19880

This doc describes the interface to read and write MAT files in C/C++:

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f39876.html#f13830

Upvotes: 0

Related Questions