MATLAB: How to resize an mxArray

cMATLABmexmxarrayreallocateresize

I'm trying to write a C program that reads some data and writes to a mat-file. But I don't know how many elements to allocate for the mxArrays until all of the data has been read. I'm thinking I would allocate the mxArrays in chunks, growing their size as needed but I don't see any mx API function that would do this. Here's a skeleton:
/* Open MAT output file */
pmat = matOpen(ofile, "w"));
NROWS = 10000;
mxA = mxCreateDoubleMatrix(NROWS,1,mxREAL);
a = mxGetPr(mxA);
/* read all data and populate mxArray */
nrec = 0;
while (!EOF)
{
/* read some data from file... */
/* increase size of mxArray if needed */
if (nrec > mxGetM(mxA))
{
mxSetM(mxA,mxGetM(mxA)+NROWS); /* but this doesn't increase the size of the pr array */
???
}
/* add value to my mxArray */
a[nrec++] = mydata;
}
/* write to mat-file */
mxSetM(mxA, nrec);
matPutVariable(pmat, "a", mxA);
matClose(pmat);
mxDestroyArray(mxA);
I know there is mxRealloc, but that allocates by number of bytes. I have tried
mxSetM(mxA,mxGetM(mxA)+NROWS);
mxRealloc((void*)a, mxGetM(mxA)*sizeof(double))
Doesn't work. Program crashes. I would think there must be an easy way to do this by the number of elements but can't seem to find an answer. What am I missing?

Best Answer

You are missing a step. After you do the mxRealloc, you need to set this new pointer into the mxArray. E.g.,
a = mxRealloc(a, mxGetM(mxA)*sizeof(double));
mxSetPr(mxA,a);
Also, your test is inconsistent. The variable nrec is a 0-based index for C array indexing, but the result of mxGetM is 1-based for MATLAB array indexing. So you should change this:
if (nrec > mxGetM(mxA))
to this:
if (nrec == mxGetM(mxA))
I.e., with your current code nrec is allowed to be equal to mxGetM(mxA), but this is 1 index beyond the actual memory allocated for 0-based indexing.