Writing MAT file from c++. I have fully compiled code but values come out odd.
Show older comments
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;
}
Accepted Answer
More Answers (1)
Walter Roberson
on 26 Jun 2012
1 vote
You have mxCreateDoubleMatrix but you write "float" (single precision) into its data pointer.
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!