Matlab API reading .mat file from c++, using STL container

前端 未结 3 1863
予麋鹿
予麋鹿 2020-12-05 08:58

I have to read some .mat data files from c++, I read through the documentation, but I would like to know how to handle the data in a clean and elegant way, e.g. using std:ve

3条回答
  •  春和景丽
    2020-12-05 09:32

    Here is an example of using the MAT-API:

    test_mat.cpp

    #include "mat.h"
    #include 
    #include 
    
    void matread(const char *file, std::vector& v)
    {
        // open MAT-file
        MATFile *pmat = matOpen(file, "r");
        if (pmat == NULL) return;
    
        // extract the specified variable
        mxArray *arr = matGetVariable(pmat, "LocalDouble");
        if (arr != NULL && mxIsDouble(arr) && !mxIsEmpty(arr)) {
            // copy data
            mwSize num = mxGetNumberOfElements(arr);
            double *pr = mxGetPr(arr);
            if (pr != NULL) {
                v.reserve(num); //is faster than resize :-)
                v.assign(pr, pr+num);
            }
        }
    
        // cleanup
        mxDestroyArray(arr);
        matClose(pmat);
    }
    
    int main()
    {
        std::vector v;
        matread("data.mat", v);
        for (size_t i=0; i

    First we build the standalone program, and create some test data as a MAT-file:

    >> mex -client engine -largeArrayDims test_mat.cpp
    
    >> LocalDouble = magic(4)
    LocalDouble =
        16     2     3    13
         5    11    10     8
         9     7     6    12
         4    14    15     1
    
    >> save data.mat LocalDouble
    

    Now we run the program:

    C:\> test_mat.exe
    16 
    5 
    9 
    4 
    2 
    11 
    7 
    14 
    3 
    10 
    6 
    15 
    13 
    8 
    12 
    1 
    

提交回复
热议问题