How do I resize an mxArray
Show older comments
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?
Accepted Answer
More Answers (0)
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!