Writing MAT file from c++. I have fully compiled code but values come out odd.

조회 수: 11 (최근 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;
}

채택된 답변

James Tursa
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
Jon
Jon 2012년 6월 26일
This is wonderful. Thanks! (The typo was from deleting a lot of other variables)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 6월 26일
You have mxCreateDoubleMatrix but you write "float" (single precision) into its data pointer.
  댓글 수: 1
Jon
Jon 2012년 6월 26일
Holy crap, this is what I get for not reading the API carefully enough. Thank you!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by