Writing MAT file from c++. I have fully compiled code but values come out odd.
1 次查看(过去 30 天)
显示 更早的评论
So I have a regular old c++ array of size 1 by 2919111 and I write this to a mat file using the matimport.c example. Where n(1) = 7.734261 in memory when written to the mat file it's value is 9.624101589057462e+04 and all other array entries are equal to zero though the mat file has the correct array size. Anyone have any ideas?
#include "creader.h"
#include "mat.h"
#include "matrix.h"
using namespace std;
int main(int argc, char *argv[]) {
/* MAT-file */
char * pch;
char fname[50];
strcpy(fname,argv[1]);
strcat(fname,".mat");
pch = strstr (fname,"CER");
strncpy (pch,"cct",3);
MATFile *pmat;
const char *myFile = fname;
/* Variables for mxArrays */
mxArray *pn;
/* MATLAB variable names */
const char *myn = "n";
int status1;
/* Create and open MAT-file */
printf("Creating file %s...\n\n", myFile);
pmat = matOpen(myFile, "w");
if (pmat == NULL) {
printf("Error creating file");
return(EXIT_FAILURE);
}
float * n = new float [k];
_ STUFF TO FILL IN n_
/* Create mxArrays and copy external data */
pn = mxCreateDoubleMatrix(1,k,mxREAL);
if ((pn == NULL) {
printf("Unable to create mxArray with mxCreateDoubleMatrix\n");
return(EXIT_FAILURE);
}
memcpy((void *)(mxGetPr(pn)), (void *)n, sizeof(n));
/* Write data to MAT-file */
status1 = matPutVariable(pmat, myn, pn);
if ((status1) != 0) {
printf("Error writing.\n");
return(EXIT_FAILURE);
}
/* Clean up */
mxDestroyArray(pn);
return 0;
}
0 个评论
采纳的回答
James Tursa
2012-6-26
Walter has noted your problem already, but I would point out that this is not the best way to go about things. You can avoid the new, delete (which you forgot), and memcpy simply by changing this
float * n = new float [k];
_ STUFF TO FILL IN n_
/* Create mxArrays and copy external data */
pn = mxCreateDoubleMatrix(1,k,mxREAL);
if (pn == NULL) { /* you had a typo here */
printf("Unable to create mxArray with mxCreateDoubleMatrix\n");
return(EXIT_FAILURE);
}
memcpy((void *)(mxGetPr(pn)), (void *)n, sizeof(n));
to this:
pn = mxCreateDoubleMatrix(1,k,mxREAL);
if (pn == NULL) {
printf("Unable to create mxArray with mxCreateDoubleMatrix\n");
return(EXIT_FAILURE);
}
double *n = mxGetPr(pn);
_ STUFF TO FILL IN n_
更多回答(1 个)
Walter Roberson
2012-6-26
You have mxCreateDoubleMatrix but you write "float" (single precision) into its data pointer.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!