MATLAB: MxCreateNumericArray: increase array size at run-time

increasemxcreatenumericarraysize;

hi, once the array is created using mxCreateNumericArray, is there a way to increase the array size afterwards?
mwSize* nDimSizes = new mwSize[2];
nDimSizes[0] = 1771;
nDimSizes[1] = 1;
mxArray* pArray = mxCreateNumericArray(2, nDimSizes, mxDOUBLE_CLASS, mxREAL);

Best Answer

The only way is to reallocate the data memory and copy all of the data values over to the new memory area. If you increase the size in such a way that the original data remains in the same place relative to the start of the memory block, then you can simply use mxRealloc to accomplish both tasks at once. E.g., if you were to add 1 row and 1 column and keep the original data at the top of the first column, then this would do it:
nDimSizes[0] = 1772; // <-- add a row
nDimSizes[1] = 2; // <-- add a column
mxSetDimensions( pArray, nDimSizes, 2 ); // <-- Set new dimensions
mxSetPr( pArray, mxRealloc( mxGetPr(pArray), 8*mxGetNumberOfElements(pArray) ) ); // <-- Realloc data memory
mxRealloc will automatically free the old data block. Also, the mxSetPr function will automatically remove the address returned by mxRealloc from the garbage collection list, so you don't need to use mexMakeMemoryPersistent on it. It is not stated in the documentation if the additional memory coming from mxRealloc is set to 0's or not. So if you need this to be the case then you might want to add code to 0 it out. Also, the above assumes a mex routine. If this is an Engine application, then you would need to add code to check the return values of mxSetDimensions and mxRealloc.
However, if any of the data changes position relative to the start of the memory block, then you will need to manually copy the data over one element at a time rather than using mxRealloc. I.e., you would use mxMalloc to get a new memory block, followed by code to copy the elements over from the old memory block to the new memory block in their new locations, followed by mxFree on the old memory block, followed by mxSetPr with the new memory block. How you would do the element-by-element copy would depend on what the new array size is and how you want the old data re-mapped into the new memory.