Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

matlab

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 ?

like image 626
iceman Avatar asked Oct 29 '25 21:10

iceman


2 Answers

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

like image 119
user244795 Avatar answered Oct 31 '25 12:10

user244795


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

Edit: Sorry, the link got corrupted.

like image 23
P-Nuts Avatar answered Oct 31 '25 12:10

P-Nuts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!