MATLAB Application Program Interface | Search  Help Desk |
mxCreateStructArray | Examples See Also |
Create an unpopulated N-dimensional structure mxArray
#include "matrix.h" mxArray *mxCreateStructArray(int ndim, const int *dims, int nfields, const char **field_names);ndim
ndims
to be less than 2, mxCreateNumericArray
creates a two-dimensional mxArray
.
dims
dims[0]
to 5 and dims[1]
to 7 establishes a 5-by-7 mxArray
. Typically, the dims
array should have ndim
elements.
nfields
mxArray
, if successful; otherwise, returns NULL
. The most likely cause of failure is insufficient heap space to hold the returned mxArray
.
Call mxCreateStructArray
to create an unpopulated structure mxArray
. Each element of a structure mxArray
contains the same number of fields (specified in nfields)
. Each field has a name; the list of names is specified in field_names.
A structure mxArray
in MATLAB is conceptually identical to an array of structs
in the C language.
Each field holds one mxArray
pointer.
mxCreateStructArray
initializes each field to NULL
. Call mxSetField
or mxSetFieldByNumber
to place a non-NULL
mxArray
pointer in a field.
When you finish using the returned structure mxArray
, call mxDestroyArray
to reclaim its space.
Create a 2-by-3 structure mxArray, in which each element contains two fields (the "name"
field and the "grade" field). Then, populate the field with data. Each "name"
field holds a string mxArray
and each "grade"
field holds a numeric mxArray
.
#define rows 3 #define cols 2 #define TOTAL_ELEMENTS (rows * cols) int ndim = 2, dims[2] = {rows, cols}; int number_of_fields=2; const char *field_names[] = {"name", "grade"}; const char *names_values[] = {"Rachel","Aysha","Maria", "Per","Martin","Bob"}; double grades_values[] = {100, 95, 95, 97, 98, 96}; double *pr; mxArray *field_value, *struct_array_ptr; int index; unsigned char *start_of_pr, *start_of_pi; mxArray *array_ptr; size_t bytes_to_copy; /* Create a 2-by-3 array of structs. */ struct_array_ptr = mxCreateStructArray(ndim, dims, number_of_fields, field_names); /* Populate the 6 name fields. */ for (index=0; index<TOTAL_ELEMENTS; index++) { field_value = mxCreateString(names_values[index]); mxSetField(struct_array_ptr, index, "name", field_value); /* mxDestroyArray(field_value); */ } /* Populate the 6 grade fields. */ for (index=0; index<TOTAL_ELEMENTS; index++) { field_value = mxCreateDoubleMatrix(1, 1, mxREAL); pr = mxGetPr(field_value); pr[0] = grades_values[index]; mxSetField(struct_array_ptr, index, "grade", field_value); /* mxDestroyArray(field_value); */ }For an additional example, see
mxcreatestructarray.c
in the mx
subdirectory of the examples
directory.
mxCreateFull
, mxDestroyArray
, mxSetNzmax