Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "mex.h"
- void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- {
- // check number of arguments
- if (nrhs != 3) {
- mexErrMsgIdAndTxt("MATLAB:minrhs", "Not enough input arguments.");
- }
- if (nlhs > 1) {
- mexErrMsgIdAndTxt("MATLAB:maxlhs", "Too many output arguments.");
- }
- if (nlhs == 0) {
- mexWarnMsgIdAndTxt("MATLAB:MustHaveOutput", "my_setfield must be called with an output.");
- }
- // check type of input arguments
- if (!mxIsStruct(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1) {
- mexErrMsgIdAndTxt("MATLAB:mustBeStruct", "Not a scalar structure.");
- }
- if (!mxIsChar(prhs[1]) || mxGetM(prhs[1])!=1) {
- mexErrMsgIdAndTxt("MATLAB:mustBeFieldName", "Not a valid field name.");
- }
- // create output structure
- plhs[0] = mxDuplicateArray(prhs[0]);
- // name of field
- char *fieldname = mxArrayToString(prhs[1]);
- if (fieldname == NULL) {
- mexErrMsgIdAndTxt("MATLAB:NULL", "NULL pointer.");
- }
- // get corresponding field number
- int fieldnum = mxGetFieldNumber(plhs[0], fieldname);
- if (fieldnum == -1) {
- // add new field
- fieldnum = mxAddField(plhs[0], fieldname);
- } else {
- // free existing field value
- mxArray *pm = mxGetFieldByNumber(plhs[0], 0, fieldnum);
- if (pm != NULL) {
- mxDestroyArray(pm);
- }
- }
- mxFree(fieldname);
- // set field value
- if (fieldnum == -1) {
- mexErrMsgIdAndTxt("MATLAB:error", "Invalid field number.");
- }
- mxSetFieldByNumber(plhs[0], 0, fieldnum, mxDuplicateArray(prhs[2]));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement