Writing mat file from C++ using API, empty matrix
Mostrar comentarios más antiguos
I wish to write an Eigen type Matrix to a mat file as seen in this code. To simplify things, in the code below I'm simply attempting to write the content of the vector vTest. After running the code, the .mat file variable contains a 1 x 5 matrix, however all entires are 0! When calling mxCreateDoubleMatrix I know that all entires are initialised to 0; I think this means none of the data is copied by memcpy()?
Note that by simply looping through data2 I can tell that it indeed contains 1,2,3,4,5 before memcpy() is called. I also tried with a one dimensional array (data2) - same problem.
(I'm using Visual Studio 2015)
Can anyone suggest why this isn't working?
void matLink::matWrite(const char *file, const char* varName, Eigen::MatrixXd data)
{
std::vector<double> vTest = { 1, 2, 3, 4, 5 };
MATFile *pMat = matOpen(file, "w");
if (pMat == NULL) { std::cerr << "matOpen: Failed to open mat file for writing\n"; return; }
mxArray * pArr;
const int rows = 1;
const int columns = vTest.size();
pArr = mxCreateDoubleMatrix(rows, columns, mxREAL);
double **data2 = new double*[rows];
for (int i = 0; i < rows; i++) {
data2[i] = new double[columns];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
data2[i][j] = vTest[j];
}
}
memcpy((void*)mxGetPr(pArr), (void*)data2, sizeof(data2));
if (matPutVariable(pMat, varName, pArr) != 0) {
std::cerr << "matPutVariable: ERROR" << std::endl;
}
mxDestroyArray(pArr);
if (matClose(pMat) != 0) {
std::cerr << "matWrite: ERROR closing file " << file << std::endl;
}
}
2 comentarios
Mahendrababu
el 2 de Nov. de 2023
How can I avoid Row and Column loops in above program?
James Tursa
el 14 de Nov. de 2023
The answer and comments below describe how to use memcpy. That technique could be used to avoid the loops also.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre MATLAB Support for MinGW-w64 C/C++ Compiler en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!