MATLAB Application Program Interface | Search  Help Desk |
mxGetFieldNameByNumber | Examples See Also |
Get a field name, given a field number in a structure array
#include "matrix.h" const char *mxGetFieldNameByNumber(const mxArray *array_ptr, int field_number);array_ptr
mxArray
.
field_number
field_number
to 0; to get the name of the second field, set field_number
to 1; and so on.
A pointer to the n
th field name, on success. Returns NULL
on failure. Common causes of failure include:
array_ptr
that does not point to a structure mxArray
. Call mxIsStruct
to determine if array_ptr
points to a structure mxArray
.
field_number
greater than or equal to the number of fields in the structure mxArray
. (Remember that field_number
0 symbolizes the first field, so index
N-1
symbolizes the last field.)
mxMAXNAM
characters long.
Call mxGetFieldNameByNumber
to get the name of a field in the given structure mxArray
. A typical use of mxGetFieldNameByNumber
is to call it inside a loop in order to get the names of all the fields in a given mxArray
.
Consider a MATLAB
structure initialized to
>> patient.name = 'John Doe'; >> patient.billing = 127.00; >> patient.test = [79 75 73; 180 178 177.5; 220 210 205];The
field_number
0 represents the field name "name
"; field_number
1 represents field name "billing
"; field_number
2 represents field name "test
". A field_number
other than 0, 1, or 2 causes mxGetFieldNameByNumber
to return NULL
.
Create a MEX-file named SeeStruc
that tells you the names of each field in an input structure mxArray
:
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { int number_of_fields, field_num; const char *field_name; if (mxIsStruct(prhs[0])) { number_of_fields = mxGetNumberOfFields(prhs[0]); if (number_of_fields == 0) mexWarnMsgTxt("This structure has no fields."); else { /* Get the first field name, then the second, and so on. */ for (field_num=0; field_num<number_of_fields; field_num++) { field_name = mxGetFieldNameByNumber(prhs[0], field_num); mexPrintf("%s\n", field_name); } } } else mexErrMsgTxt("You must pass a structure mxArray."); }In MATLAB, create a structure named
patient
>> patient.name = 'John Doe'; >> patient.billing = 127.00; >> patient.test = [79 75 73; 180 178 177.5; 220 210 205];Passing
patient
to SeeStruc
yields
>> SeeStruc(patient) The three fields of patient are: name billing testFor an additional example, see
mxgetfieldnamebynumber.c
in the mx
subdirectory of the examples
directory.
mxGetField
, mxIsStruct
, mxSetField