| MATLAB Application Program Interface Reference | Help Desk |
mxSetField
Set a field value of a structure array, given a field name and an index
#include "matrix.h" void mxSetField(mxArray *array_ptr, int index, const char *field_name, mxArray *value);array_ptr
Pointer to a structure mxArray. Call mxIsStruct to determine if array_ptr points to a structure mxArray.
The desired element. The first element of an mxArray has an index of 0, the second element has an index of 1, and the last element has an index of N-1, where N is the total number of elements in the structure mxArray. See mxCalcSingleSubscript for details on calculating an index.
The name of the field whose value you are assigning. Call mxGetFieldNameByNumber or mxGetFieldNumber to determine existing field_names.
Pointer to the mxArray you are assigning.
mxSetField to assign a value to the specified element of the specified field. In pseudo-C terminology, mxSetField performs the assignment
array_ptr[index].field_name = value;If there is already a value at the given position, the
value pointer you specified overwrites the old value pointer. However, mxSetField does not free the dynamic memory that the old value pointer pointed to. Consequently, you should typically free this old mxArray immediately before or after calling mxSetField.
Consider a function that expects to receive a structure mxArray containing a speed field. The speed field contains a numeric scalar. The function calls mxSetField to change the value in the speed field to a string mxArray.
void RedoTheSpeedField(mxArray *array_ptr)
{
mxArray *old_field, *low_array_ptr, *high_array_ptr;
double wind_speed_as_a_number;
int index, number_of_elements;
high_array_ptr = mxCreateString("high");
low_array_ptr = mxCreateString("low");
/* Loop through each element of the structure. */
number_of_elements = mxGetM(array_ptr) * mxGetN(array_ptr);
for (index=0; index<number_of_elements; index++) {
/* Get the value in the "speed" field at this index. */
old_field = mxGetField(array_ptr, index, "speed");
/* The returned "field" is a pointer to a scalar mxArray.
Get the value associated with the scalar mxArray. */
if (old_field) {
wind_speed_as_a_number = mxGetScalar(old_field);
/* Assign the new field to the structure. */
if (wind_speed_as_a_number > 15)
mxSetField(array_ptr, index, "speed", high_array_ptr);
else
mxSetField(array_ptr, index, "speed", low_array_ptr);
/* Deallocate the memory taken up by the previous field value. */
mxDestroyArray(old_field);
}
else
/* Issue a warning message about a missing 'speed' field. */
For an additional example, see mxSetField.c in the mx subdirectory of the examples directory.
mxCreateStructArray, mxCreateStructMatrix, mxGetField, mxGetFieldByNumber, mxGetFieldNameByNumber, mxGetFieldNumber, mxGetNumberOfFields, mxIsStruct, mxSetFieldByNumber