SHARE
TWEET

my_setfield.cpp

a guest Jul 20th, 2014 384 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "mex.h"
  2.  
  3. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  4. {
  5.     // check number of arguments
  6.     if (nrhs != 3) {
  7.         mexErrMsgIdAndTxt("MATLAB:minrhs", "Not enough input arguments.");
  8.     }
  9.     if (nlhs > 1) {
  10.         mexErrMsgIdAndTxt("MATLAB:maxlhs", "Too many output arguments.");
  11.     }
  12.     if (nlhs == 0) {
  13.         mexWarnMsgIdAndTxt("MATLAB:MustHaveOutput", "my_setfield must be called with an output.");
  14.     }
  15.    
  16.     // check type of input arguments
  17.     if (!mxIsStruct(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1) {
  18.         mexErrMsgIdAndTxt("MATLAB:mustBeStruct", "Not a scalar structure.");
  19.     }
  20.     if (!mxIsChar(prhs[1]) || mxGetM(prhs[1])!=1) {
  21.         mexErrMsgIdAndTxt("MATLAB:mustBeFieldName", "Not a valid field name.");
  22.     }
  23.    
  24.     // create output structure
  25.     plhs[0] = mxDuplicateArray(prhs[0]);
  26.    
  27.     // name of field
  28.     char *fieldname = mxArrayToString(prhs[1]);
  29.     if (fieldname == NULL) {
  30.         mexErrMsgIdAndTxt("MATLAB:NULL", "NULL pointer.");
  31.     }
  32.    
  33.     // get corresponding field number
  34.     int fieldnum = mxGetFieldNumber(plhs[0], fieldname);
  35.     if (fieldnum == -1) {
  36.         // add new field
  37.         fieldnum = mxAddField(plhs[0], fieldname);
  38.     } else {
  39.         // free existing field value
  40.         mxArray *pm = mxGetFieldByNumber(plhs[0], 0, fieldnum);
  41.         if (pm != NULL) {
  42.             mxDestroyArray(pm);
  43.         }
  44.     }
  45.     mxFree(fieldname);
  46.    
  47.     // set field value
  48.     if (fieldnum == -1) {
  49.         mexErrMsgIdAndTxt("MATLAB:error", "Invalid field number.");
  50.     }
  51.     mxSetFieldByNumber(plhs[0], 0, fieldnum, mxDuplicateArray(prhs[2]));
  52. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top