Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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;
}

Akzeptierte Antwort

James Tursa
James Tursa am 26 Jun. 2012
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_

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 26 Jun. 2012
You have mxCreateDoubleMatrix but you write "float" (single precision) into its data pointer.

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by