MATLAB Application Program Interface | Search  Help Desk |
mxSetDimensions | Examples See Also |
Modify the number of dimensions and/or the size of each dimension
#include "matrix.h" int mxSetDimensions(mxArray *array_ptr, const int *size, int ndims);array_ptr
mxArray
.
ndims
ints
. Each element in the array holds the size of a particular dimension. The first element holds the number of elements in the first dimension (rows); the second element holds the number of elements in the second dimension, and so on.
0 on success, and 1 on failure. mxSetDimensions
allocates heap space to hold the input size array. So it is possible (though extremely unlikely) that increasing the number of dimensions can cause the system to run out of heap space.
Call mxSetDimensions
to reshape an existing mxArray
. mxSetDimensions
is similar to mxSetM
and mxSetN
; however, mxSetDimensions
provides greater control for reshaping mxArrays
that have more than two-dimensions.
mxSetDimensions
does not allocate or deallocate any space for the pr
or pi
arrays. Consequently, if your call to mxSetDimensions
increases the number of elements in the mxArray
, then you must enlarge the pr
(and pi
, if it exists) arrays accordingly.
If your call to mxSetDimensions
reduces the number of elements in the mxArray
, then you can optionally reduce the size of the pr
and pi
arrays.
Create a populated 3-by-2 mxArray
. Then, call mxSetDimensions
to expand the mxArray
to 4-by-3-by-2. Preserve the original 3-by-2 data as the first page of the expanded mxArray
.
#define ROWS 3
#define COLS 2
#define TOTAL_ELEMENTS (ROWS * COLS)
#define NEW_PAGES 4
#define NEW_ROWS 3
#define NEW_COLS 2
#define TOTAL_NEW_ELEMENTS (NEW_PAGES * NEW_ROWS * NEW_COLS)
mxArray *array_ptr;
static double real_data[] = {5.2, 7.8, 4.3, 9.3, 8.2, 7.1};
int new_ndims=3;
int new_dims[3]={NEW_PAGES, NEW_ROWS, NEW_COLS};
double *start_of_new_pr, *start_of_old_pr, *pr;
/* Create a 3-by-2 array named "Apricot" */
array_ptr = mxCreateDoubleMatrix(ROWS, COLS, mxREAL);
pr = mxGetPr(array_ptr);
memcpy((void *)pr,(const void *)real_data,
ROWS*COLS*sizeof(double));
mxSetName(array_ptr, "Apricots");
...
/* Change the dimensions of "Apricots" from 3-by-2 to
4-by-3-by-2. */
mxSetDimensions
(array_ptr, new_ndims, new_dims);
/* Allocate space to hold 24 data elements. */
start_of_new_pr = mxCalloc(TOTAL_NEW_ELEMENTS,
sizeof(double));
/* Copy the old real_data to the beginning of the new section. */
start_of_old_pr = mxGetPr(array_ptr);
memcpy(start_of_new_pr, start_of_old_pr, TOTAL_ELEMENTS);
/* Deallocate the space held by the old pr. */
mxFree(start_of_old_pr);
/* Associate the new data section with the array_ptr. */
mxSetPr(array_ptr, start_of_new_pr);
...
For an additional example, see mxsetdimensions.c
in the mx
subdirectory of the examples
directory.
mxGetNumberOfDimensions
, mxSetM
, mxSetN