0

I have quite a big 2D vector of data of results that I want to write into a mat file. I'm quite new to C++ and I read some tutorials on how to use the MAT-File APIs and I understood the syntax must be something of the sort:

MATFile *pmat;
vector<double> data{....};
pmat=matOpen("ResultLog.mat", "w");

mxArray *A;
A=mxCreateDoubleMatrix(1, columns, mxREAL);
memcpy(mxGetPr(A), data, columns * sizeof(double));
matPutVariable(pmat, "NameOfDataVariable", A);

matClose(pmat);
mxDestroyArray(A);

My problem is that since I have quite some data to log I would really like to put it into a loop. However how would I be able to change the NameOfDataVariable for each loop ? Or do I have to enter each row of data into the mat file separately ? Like I said I'm quite new to this so Im sorry if its a silly question. Does anyone have any suggestions?

  • You'll find an appropriate [answer here](http://stackoverflow.com/questions/191757/c-concatenate-string-and-int/900035#900035). There's explained how you can e.g. use a loop counter to change the string (`const char*`) value you're going to pass to the `matPutVariable()` function. – πάντα ῥεῖ Jun 19 '14 at 12:38

1 Answers1

2

You can do e.g. as follows

MATFile *pmat;
vector<double> data{....};
pmat=matOpen("ResultLog.mat", "w");

// I actually don't know what loop conditions you have but
// this should give you an idea
int cnt = 0;    
for(vector<double>::iterator it = data.begin();
    it != data.end();
    ++it,++cnt) {
    mxArray *A;
    A=mxCreateDoubleMatrix(1, columns, mxREAL);
    memcpy(mxGetPr(A), *it, columns * sizeof(double));
    std::ostringstream varname;
    varname << "NameOfDataVariable" << cnt;
    matPutVariable(pmat, varname.str().c_str(), A);
    mxDestroyArray(A);
}

matClose(pmat);
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190