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!