Writing mat file from C++ using API, empty matrix
显示 更早的评论
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 个评论
Mahendrababu
2023-11-2
How can I avoid Row and Column loops in above program?
James Tursa
2023-11-14
The answer and comments below describe how to use memcpy. That technique could be used to avoid the loops also.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 MATLAB Support for MinGW-w64 C/C++ Compiler 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!