4

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 ?

3 Answers 3

2

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;
}

Sign up to request clarification or add additional context in comments.

Comments

1

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

Edit: Sorry, the link got corrupted.

1 Comment

The documentation link you followed is no longer valid.
0

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

1 Comment

I read the docs but I'm a little confused. How can i import data from the mxarray data structure to a primitive data structure like a multi-dim double array ? can anyone give me a code snippet..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.