PetscErrorCode DMView_DA_Matlab(DM da,PetscViewer viewer) { PetscErrorCode ierr; PetscMPIInt rank; PetscInt dim,m,n,p,dof,swidth; DMDAStencilType stencil; DMBoundaryType bx,by,bz; mxArray *mx; const char *fnames[] = {"dimension","m","n","p","dof","stencil_width","bx","by","bz","stencil_type"}; PetscFunctionBegin; ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)da),&rank);CHKERRQ(ierr); if (!rank) { ierr = DMDAGetInfo(da,&dim,&m,&n,&p,0,0,0,&dof,&swidth,&bx,&by,&bz,&stencil);CHKERRQ(ierr); mx = mxCreateStructMatrix(1,1,8,(const char**)fnames); if (!mx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Unable to generate MATLAB struct array to hold DMDA informations"); mxSetFieldByNumber(mx,0,0,mxCreateDoubleScalar((double)dim)); mxSetFieldByNumber(mx,0,1,mxCreateDoubleScalar((double)m)); mxSetFieldByNumber(mx,0,2,mxCreateDoubleScalar((double)n)); mxSetFieldByNumber(mx,0,3,mxCreateDoubleScalar((double)p)); mxSetFieldByNumber(mx,0,4,mxCreateDoubleScalar((double)dof)); mxSetFieldByNumber(mx,0,5,mxCreateDoubleScalar((double)swidth)); mxSetFieldByNumber(mx,0,6,mxCreateDoubleScalar((double)bx)); mxSetFieldByNumber(mx,0,7,mxCreateDoubleScalar((double)by)); mxSetFieldByNumber(mx,0,8,mxCreateDoubleScalar((double)bz)); mxSetFieldByNumber(mx,0,9,mxCreateDoubleScalar((double)stencil)); ierr = PetscObjectName((PetscObject)da);CHKERRQ(ierr); ierr = PetscViewerMatlabPutVariable(viewer,((PetscObject)da)->name,mx);CHKERRQ(ierr); } PetscFunctionReturn(0); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs != 0) mexErrMsgTxt("Wrong number of arguments"); cufftType_t dummy; const char *field_names[] = { "CUFFT_R2C", "CUFFT_C2R", "CUFFT_C2C" }; mxArray *r; mwSize dims[2] = { 1, 1 }; mxArray *field_value; r = mxCreateStructArray(2, dims, 3, field_names); field_value = mxCreateDoubleScalar((unsigned int) CUFFT_R2C); mxSetFieldByNumber(r, 0, 0, field_value); field_value = mxCreateDoubleScalar((unsigned int) CUFFT_C2R); mxSetFieldByNumber(r, 0, 1, field_value); field_value = mxCreateDoubleScalar((unsigned int) CUFFT_C2C); mxSetFieldByNumber(r, 0, 2, field_value); plhs[0] = r; }
void gpc_write_polygon_MATLAB(mxArray *plhs, gpc_polygon *p) { int c, v; int dims[2]; mxArray *field_x, *field_y, *field_hole; const char *field_names[] = {"x","y","hole"}; dims[0]=1; dims[1]=p->num_contours; for (c=0; c < p->num_contours; c++) { field_x = mxCreateDoubleMatrix(p->contour[c].num_vertices,1,mxREAL); field_y = mxCreateDoubleMatrix(p->contour[c].num_vertices,1,mxREAL); for (v= 0; v < p->contour[c].num_vertices; v++) { ((double*)mxGetPr(field_x))[v]=p->contour[c].vertex[v].x; ((double*)mxGetPr(field_y))[v]=p->contour[c].vertex[v].y; } mxSetFieldByNumber(plhs,c,0,field_x); mxSetFieldByNumber(plhs,c,1,field_y); field_hole = mxCreateDoubleMatrix(1,1,mxREAL); ((double*)mxGetPr(field_hole))[0]=p->hole[c]; mxSetFieldByNumber(plhs,c,2,field_hole); } gpc_free_polygon(p); }
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { int structNum = sizeof(friends)/sizeof(struct phonebook); // 結構陣列的長度 int fieldNum = sizeof(fieldNames)/sizeof(*fieldNames); // 欄位的個數 int dims[2] = {1, structNum}; // 結構陣列的維度 int i, nameFieldIndex, phoneFieldIndex; // 檢查輸入和輸出參數的個數 if (nrhs>0) mexErrMsgTxt("No input argument required."); if (nlhs>1) mexErrMsgTxt("Too many output arguments."); // 產生輸出結構陣列 OUT = mxCreateStructArray(2, dims, fieldNum, fieldNames); // 取得欄位名稱對應的索引值,以便使用 mxSetFieldByNumber() 對欄位值進行設定 nameFieldIndex = mxGetFieldNumber(OUT, "name"); phoneFieldIndex = mxGetFieldNumber(OUT, "phone"); // 填入 MATLAB 結構陣列的欄位值 for (i=0; i<structNum; i++) { mxArray *fieldValue; // 填入欄位名稱 name 的值(有兩種方法) // mxSetField(OUT, i, "name", mxCreateString(friends[i].name)); // 方法一:效率較低 mxSetFieldByNumber(OUT, i, nameFieldIndex, mxCreateString(friends[i].name)); // 方法二:效率較高 // 填入欄位名稱 phone 的值(有兩種方法) fieldValue = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(fieldValue) = friends[i].phone; // mxSetField(OUT, i, "phone", fieldValue); // 方法一:效率較低 mxSetFieldByNumber(OUT, i, phoneFieldIndex, fieldValue); // 方法二:效率較高 } }
mxArray *createFromNifti1(nifti_1_header *NH) { mxArray *S, *A; double *a; int i,dims; S = mxCreateStructMatrix(1, 1, nifti1_num_fields, nifti1_field_names); dims = NH->dim[0]; /* dim */ A = mxCreateDoubleMatrix(dims, 1, mxREAL); a = mxGetPr(A); for (i=0;i<dims;i++) { a[i] = NH->dim[i+1]; } mxSetFieldByNumber(S, 0, 0, A); /* pixdim */ A = mxCreateDoubleMatrix(dims, 1, mxREAL); a = mxGetPr(A); for (i=0;i<dims;i++) { a[i] = NH->pixdim[i+1]; } mxSetFieldByNumber(S, 0, 1, A); /* datatype */ A = mxCreateDoubleScalar(NH->datatype); mxSetFieldByNumber(S, 0, 2, A); return S; }
void CreateMeasStructure( std::vector<MRIMeasurement>& meas_vector, mxArray** meas_struct ) { // create structure const char* field_names [] = { "measurement", "indicies" }; mwSize struct_dims = meas_vector.size(); *meas_struct = mxCreateStructArray( 1, &struct_dims, 2, field_names ); // fill structure int num_dims = MRIDimensions::GetNumDims(); for( unsigned int i = 0; i < meas_vector.size(); i++ ) { // fill measurement mxArray mxSetFieldByNumber( *meas_struct, i, 0, MexData::ExportMexArray( meas_vector[i].GetData() ) ); // create index mxArray //MRIDimensions data_size = meas_vector[i].GetData().Size(); MRIDimensions data_size = meas_vector[i].GetIndex(); mwSize dims = num_dims + 1; // we need all the dim indicies plus meas time mxArray* meas_array = mxCreateNumericArray( 1, &dims, mxSINGLE_CLASS, mxREAL ); float* index_data = (float*)mxGetPr( meas_array ); int dim_size; for( int j = 0; j < num_dims; j++ ) { data_size.GetDim( j, dim_size ); // 1 based matlab matrix indicies... index_data[j] = dim_size+1; } index_data[num_dims] = meas_vector[i].meas_time; mxSetFieldByNumber( *meas_struct, i, 1, meas_array ); } }
static mxArray* resize_property_structure(mxArray *pprop, int size) { mxArray *newpprop; mxArray *pattr, *pvalue; int nump, k; const char *fields[] = {"attr","name"}; /* new structure array */ newpprop = mxCreateStructMatrix(1,size, 2, fields); /* copy over the old structure array */ if (pprop == NULL) nump = 0; /* first one */ else nump = mxGetM(pprop) * mxGetN(pprop); for (k=0; k<nump; k++) { pattr = mxGetFieldByNumber(pprop, k, 0); pvalue = mxGetFieldByNumber(pprop, k, 1); mxSetFieldByNumber(newpprop, k, 0, pattr); mxSetFieldByNumber(newpprop, k, 1, pvalue); } /* destroy the old structure array */ if (pprop != NULL) mxDestroyArray(pprop); return newpprop; }
void Problem::make_answer(std::vector<Boxes> boxes, const char *field_names[], const char *types[]) { mxArray *ans = mxCreateStructMatrix(boxes.size(), 1, 2, field_names); for (int a = 0; a < boxes.size(); ++a) { mxSetFieldByNumber(ans, a, 0, mxCreateString(types[a])); //Creates a cell matrix(boxes.size(),1) and populates it with individual boxes mxArray *boxes_mx = mxCreateCellMatrix(boxes[a].size(), 1); make_boxes_mx(boxes[a], boxes_mx); mxSetFieldByNumber(ans, a, 1, mxDuplicateArray(boxes_mx)); } plhs[0] = mxDuplicateArray(ans); };
void mexFunction (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { int i; mwIndex j; mxArray *v; const char *keys[] = { "this", "that" }; if (nrhs != 1 || ! mxIsStruct (prhs[0])) mexErrMsgTxt ("expects struct"); for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++) for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++) { mexPrintf ("field %s(%d) = ", mxGetFieldNameByNumber (prhs[0], i), j); v = mxGetFieldByNumber (prhs[0], j, i); mexCallMATLAB (0, 0, 1, &v, "disp"); } v = mxCreateStructMatrix (2, 2, 2, keys); mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1")); mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1")); mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2")); mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2")); mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3")); mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3")); mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4")); mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4")); if (nlhs) plhs[0] = v; }
BEGIN_NAMESPACE_MW_MATLAB void getEvents(MEXInputs &inputs, MEXOutputs &outputs) { boost::filesystem::path filename; std::set<unsigned int> event_codes; MWTime lower_bound, upper_bound; inputs >> filename >> event_codes >> lower_bound >> upper_bound; std::vector<int> codes; std::vector<MWTime> times; boost::container::vector<ArrayPtr> values; try { dfindex dfi(filename); DataFileIndexer::EventsIterator ei = dfi.getEventsIterator(event_codes, lower_bound, upper_bound); while (true) { EventWrapper event = ei.getNextEvent(); if (event.empty()) break; codes.push_back(event.getEventCode()); times.push_back(event.getTime()); values.push_back(convertDatumToArray(scarabDatumToDatum(event.getPayload()))); } } catch (const DataFileIndexerError &e) { throwMATLABError("MWorks:DataFileIndexerError", e.what()); } if (outputs.count() == 3) { outputs << codes; outputs << times; outputs << values; } else { const char *fieldNames[] = {"event_code", "time_us", "data"}; ArrayPtr result(throw_if_null, mxCreateStructMatrix(1, int(codes.size()), 3, fieldNames)); for (std::size_t i = 0; i < codes.size(); i++) { mxSetFieldByNumber(result.get(), i, 0, Array::createScalar(codes[i]).release()); mxSetFieldByNumber(result.get(), i, 1, Array::createScalar(times[i]).release()); mxSetFieldByNumber(result.get(), i, 2, values[i].release()); } outputs << std::move(result); } }
void addGroupMetaField(mxArray* mxGroupMeta, const GroupInfo *pg) { mxArray * thisGroupsField = setGroupMetaFields(pg, NULL, 0); // add this group as a field to mxGroupMeta unsigned fieldNum = mxAddField(mxGroupMeta, pg->name); mxSetFieldByNumber(mxGroupMeta, 0, fieldNum, thisGroupsField); }
void _testNamespaces_RTTIRegister() { const mxArray *alreadyCreated = mexGetVariablePtr("global", "gtsam_testNamespaces_rttiRegistry_created"); if(!alreadyCreated) { std::map<std::string, std::string> types; mxArray *registry = mexGetVariable("global", "gtsamwrap_rttiRegistry"); if(!registry) registry = mxCreateStructMatrix(1, 1, 0, NULL); typedef std::pair<std::string, std::string> StringPair; for(const StringPair& rtti_matlab: types) { int fieldId = mxAddField(registry, rtti_matlab.first.c_str()); if(fieldId < 0) mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly"); mxArray *matlabName = mxCreateString(rtti_matlab.second.c_str()); mxSetFieldByNumber(registry, 0, fieldId, matlabName); } if(mexPutVariable("global", "gtsamwrap_rttiRegistry", registry) != 0) mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly"); mxDestroyArray(registry); mxArray *newAlreadyCreated = mxCreateNumericMatrix(0, 0, mxINT8_CLASS, mxREAL); if(mexPutVariable("global", "gtsam_testNamespaces_rttiRegistry_created", newAlreadyCreated) != 0) mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly"); mxDestroyArray(newAlreadyCreated); } }
bool addGroupTimestampsField(mxArray* mxTrial, const GroupInfo* pg, unsigned trialIdx, timestamp_t timeTrialStart, bool useGroupPrefix, unsigned index, unsigned nSamples) { // build groupName_time field name char fieldName[MAX_SIGNAL_NAME]; if(useGroupPrefix) snprintf(fieldName, MAX_SIGNAL_NAME, "%s_time", pg->name); else strcpy(fieldName, "time"); timestamp_t *pTimestampsBase = pg->tsBuffers[trialIdx].timestamps; uint32_t nTimestampsBase = pg->tsBuffers[trialIdx].nSamples; // create the matlab array to hold the timestamps, use double as the type mxArray* mxTimestamps = mxCreateNumericMatrix(nTimestampsBase, 1, mxDOUBLE_CLASS, mxREAL); // enter the timestamps minus the trial start into the array double_t* buffer = (double_t*)mxGetData(mxTimestamps); // no offsets, subtract trial start and round to ms (should be integer anyway) for(unsigned i = 0; i < nTimestampsBase; i++) buffer[i] = pTimestampsBase[i] - timeTrialStart; // add to trial struct int fieldNum; fieldNum = mxGetFieldNumber(mxTrial, fieldName); if(fieldNum == -1) fieldNum = mxAddField(mxTrial, fieldName); mxSetFieldByNumber(mxTrial, index, fieldNum, mxTimestamps); return true; }
void addSignalMetaField(mxArray* mxSignalMeta, const SignalDataBuffer *psdb) { mxArray * thisSignalField = setSignalMetaFields(psdb, NULL, 0); // add this group as a field to mxGroupMeta unsigned fieldNum = mxAddField(mxSignalMeta, psdb->name); mxSetFieldByNumber(mxSignalMeta, 0, fieldNum, thisSignalField); }
void addResultsEntry(WIN32_FIND_DATA WFD, int cnt, mxArray *structOut, char *defaultPath) { char *buff[40], *month = "NaN"; char filename[MAX_PATH + 1]; double temp; mxArray *name, *date, *bytes, *isdir, *datenum; SYSTEMTIME stUTC, stLocal; FILETIME ftUTC, ftLocal; // File Name if (strlen(defaultPath) > 0){ PathCombine(filename, defaultPath, WFD.cFileName); name = mxCreateString(filename); } else { name = mxCreateString(WFD.cFileName); } mxSetFieldByNumber(structOut, cnt, NAMEFIELD , name); // Size (bytes) bytes = mxCreateDoubleScalar((WFD.nFileSizeHigh * (MAXDWORD+1)) + WFD.nFileSizeLow); mxSetFieldByNumber(structOut, cnt, BYTESFIELD , bytes); // Directory flag isdir = mxCreateLogicalScalar((WFD.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)); mxSetFieldByNumber(structOut, cnt, ISDIRFIELD , isdir); // Get local time ftUTC = WFD.ftLastWriteTime; FileTimeToSystemTime(&ftUTC, &stUTC); SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal); // Date string month = monthNumToStr(stLocal.wMonth); sprintf(buff,"%02d-%s-%04d %02d:%02d:%02d",stLocal.wDay,month,stLocal.wYear,stLocal.wHour,stLocal.wMinute,stLocal.wSecond); date = mxCreateString(buff); mxSetFieldByNumber(structOut, cnt, DATEFIELD , date); // Datenum SystemTimeToFileTime(&stLocal,&ftLocal); temp = (double) ftLocal.dwHighDateTime; temp = temp * ((double)MAXDWORD+1); temp = temp + ftLocal.dwLowDateTime; datenum = mxCreateDoubleScalar((temp/864000000000) + 584755); mxSetFieldByNumber(structOut, cnt, DATENUMFIELD , datenum); }
void mxSetField(mxArray *array_ptr, int lindex, const char *field_name, mxArray *value) { int field_num = mxGetFieldNumber(array_ptr, field_name); if (field_num >= 0) { mxSetFieldByNumber(array_ptr, lindex, field_num, value); } }
mxArray *emlrtMexFcnProperties(void) { const char *mexProperties[] = { "Version", "ResolvedFunctions", "EntryPoints"}; const char *epProperties[] = { "Name", "NumberOfInputs", "NumberOfOutputs", "ConstantInputs"}; mxArray *xResult = mxCreateStructMatrix(1,1,3,mexProperties); mxArray *xEntryPoints = mxCreateStructMatrix(1,1,4,epProperties); mxArray *xInputs = NULL; xInputs = mxCreateLogicalMatrix(1, 6); mxSetFieldByNumber(xEntryPoints, 0, 0, mxCreateString("naivePerfusionSSEP2X4")); mxSetFieldByNumber(xEntryPoints, 0, 1, mxCreateDoubleScalar(6)); mxSetFieldByNumber(xEntryPoints, 0, 2, mxCreateDoubleScalar(1)); mxSetFieldByNumber(xEntryPoints, 0, 3, xInputs); mxSetFieldByNumber(xResult, 0, 0, mxCreateString("8.1.0.604 (R2013a)")); mxSetFieldByNumber(xResult, 0, 1, (mxArray*)emlrtMexFcnResolvedFunctionsInfo()); mxSetFieldByNumber(xResult, 0, 2, xEntryPoints); return xResult; }
mxArray* json( const JsonValue &o ) { // convert JsonValue to Matlab mxArray siz k, m, n; mxArray *M; const char **keys; switch( o.getTag() ) { case JSON_NUMBER: return mxCreateDoubleScalar(o.toNumber()); case JSON_STRING: return mxCreateString(o.toString()); case JSON_ARRAY: { if(!o.toNode()) return mxCreateDoubleMatrix(1,0,mxREAL); JsonValue o0=o.toNode()->value; JsonTag tag=o0.getTag(); n=length(o); bool isRegular=true; for(auto i:o) isRegular=isRegular && i->value.getTag()==tag; if( isRegular && tag==JSON_OBJECT && isRegularObjArray(o) ) { m=length(o0); keys=new const char*[m]; k=0; for(auto j:o0) keys[k++]=j->key; M = mxCreateStructMatrix(1,n,m,keys); k=0; for(auto i:o) { m=0; for(auto j:i->value) mxSetFieldByNumber(M,k,m++,json(j->value)); k++; } delete [] keys; return M; } else if( isRegular && tag==JSON_NUMBER ) { M = mxCreateDoubleMatrix(1,n,mxREAL); double *p=mxGetPr(M); k=0; for(auto i:o) p[k++]=i->value.toNumber(); return M; } else { M = mxCreateCellMatrix(1,n); k=0; for(auto i:o) mxSetCell(M,k++,json(i->value)); return M; } } case JSON_OBJECT: if(!o.toNode()) return mxCreateStructMatrix(1,0,0,NULL); n=length(o); keys=new const char*[n]; k=0; for(auto i:o) keys[k++]=i->key; M = mxCreateStructMatrix(1,1,n,keys); k=0; for(auto i:o) mxSetFieldByNumber(M,0,k++,json(i->value)); delete [] keys; return M; case JSON_TRUE: return mxCreateDoubleScalar(1); case JSON_FALSE: return mxCreateDoubleScalar(0); case JSON_NULL: return mxCreateDoubleMatrix(0,0,mxREAL); default: return NULL; } }
mxArray *emlrtMexFcnProperties() { const char *mexProperties[] = { "Version", "ResolvedFunctions", "EntryPoints", "CoverageInfo", NULL }; const char *epProperties[] = { "Name", "NumberOfInputs", "NumberOfOutputs", "ConstantInputs" }; mxArray *xResult = mxCreateStructMatrix(1,1,4,mexProperties); mxArray *xEntryPoints = mxCreateStructMatrix(1,1,4,epProperties); mxArray *xInputs = NULL; xInputs = mxCreateLogicalMatrix(1, 2); mxSetFieldByNumber(xEntryPoints, 0, 0, mxCreateString("dummy")); mxSetFieldByNumber(xEntryPoints, 0, 1, mxCreateDoubleScalar(2)); mxSetFieldByNumber(xEntryPoints, 0, 2, mxCreateDoubleScalar(1)); mxSetFieldByNumber(xEntryPoints, 0, 3, xInputs); mxSetFieldByNumber(xResult, 0, 0, mxCreateString("8.5.0.197613 (R2015a)")); mxSetFieldByNumber(xResult, 0, 1, (mxArray*)emlrtMexFcnResolvedFunctionsInfo()); mxSetFieldByNumber(xResult, 0, 2, xEntryPoints); return xResult; }
mxArray *getDevices() { const char *fieldNames[] = {"index", "name", "input", "output"}; int i,numDevs; const PmDeviceInfo* info; mxArray *R; numDevs = Pm_CountDevices(); R = mxCreateStructMatrix(numDevs, 1, 4, fieldNames); for (i=0;i<numDevs;i++) { info = Pm_GetDeviceInfo(i); mxSetFieldByNumber(R, i, 0, mxCreateDoubleScalar(i+1)); mxSetFieldByNumber(R, i, 1, mxCreateString(info->name)); mxSetFieldByNumber(R, i, 2, mxCreateDoubleScalar(info->input)); mxSetFieldByNumber(R, i, 3, mxCreateDoubleScalar(info->output)); } return R; }
void SetPointerData(mxArray *A, const mxArray *data) { mxArray *address; address = mxCreateNumericMatrix(sizeof(data), 1, mxUINT8_CLASS, mxREAL); memcpy((void *)mxGetPr(address), (void *)(&data), sizeof(data)); mxSetFieldByNumber(A, 0, 0, address); }
/* * Sets the field in the struct to the given array. */ static void setArray(mxArray *pStruct, const char *fieldname, double* array, int m, int n) { mxArray* pField; pField = mxCreateDoubleMatrix(m,n,mxREAL); memcpy(mxGetPr(pField), array, n*sizeof(double)); int fieldNumber = getFieldNumber(pStruct, fieldname); mxSetFieldByNumber(pStruct, 0, fieldNumber, pField); }
int fetch_row(sqlite3_stmt *stmt, int num_columns, mxArray **array) { int i, res = sqlite3_step(stmt); if (res == SQLITE_ROW) { for (i = 0; i < num_columns; i++) { mxSetFieldByNumber(*array, 0, i, get_column(stmt, i)); } } return res; }
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { const char *field_names[] = {"name", "phone"}; struct phonebook friends[] = {{"Jordan Robert", 3386},{"Mary Smith",3912}, {"Stacy Flora", 3238},{"Harry Alpert",3077}}; mwSize dims[2] = {1, NUMBER_OF_STRUCTS }; int name_field, phone_field; mwIndex i; (void) prhs; /* Check for proper number of input and output arguments */ if (nrhs !=0) { mexErrMsgTxt("No input argument required."); } if(nlhs > 1){ mexErrMsgTxt("Too many output arguments."); } /* Create a 1-by-n array of structs. */ plhs[0] = mxCreateStructArray(2, dims, NUMBER_OF_FIELDS, field_names); /* This is redundant, but here for illustration. Since we just created the structure and the field number indices are zero based, name_field will always be 0 and phone_field will always be 1 */ name_field = mxGetFieldNumber(plhs[0],"name"); phone_field = mxGetFieldNumber(plhs[0],"phone"); /* Populate the name and phone fields of the phonebook structure. */ for (i=0; i<NUMBER_OF_STRUCTS; i++) { mxArray *field_value; /* Use mxSetFieldByNumber instead of mxSetField for efficiency mxSetField(plhs[0],i,"name",mxCreateString(friends[i].name); */ mxSetFieldByNumber(plhs[0],i,name_field,mxCreateString(friends[i].name)); field_value = mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value) = friends[i].phone; /* Use mxSetFieldByNumber instead of mxSetField for efficiency mxSetField(plhs[0],i,"name",mxCreateString(friends[i].name); */ mxSetFieldByNumber(plhs[0],i,phone_field,field_value); } }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { char *dir_name; struct file *files; int nfiles, i; const char *field_names[2]; if (nlhs > 1) mexErrMsgTxt("Too many output arguments."); if (nrhs == 0) dir_name = "."; else if (nrhs == 1) { if (mxIsChar(prhs[0]) != 1) mexErrMsgTxt("Input must be a string."); if (mxGetM(prhs[0]) != 1) mexErrMsgTxt("Input must be a row vector."); dir_name = mxArrayToString(prhs[0]); } else mexErrMsgTxt("Too many input arguments."); files = dir(dir_name, &nfiles); field_names[0] = "name"; field_names[1] = "isdir"; plhs[0] = mxCreateStructMatrix(nfiles, 1, 2, field_names); for (i = 0; i < nfiles; i++) { mxSetFieldByNumber(plhs[0], i, 0, mxCreateString(files[i].name)); mxSetFieldByNumber(plhs[0], i, 1, mxCreateLogicalScalar(files[i].is_dir)); } for (i = 0; i < nfiles; i++) mxFree(files[i].name); mxFree(files); if (nrhs > 0) mxFree(dir_name); return; }
/* * This functions adds a field to a struct. No check is performed because in * mexFunction the check was done. */ static void addField(mxArray *pStruct, const mxArray *fieldName, const mxArray *fieldValue) { int stringSize = (mxGetM(fieldName) * mxGetN(fieldName) * sizeof(mxChar)) + 1; char *name = (char *) malloc(stringSize); mxGetString(fieldName,name, stringSize); int fieldNumber = getFieldNumber(pStruct, name); mxArray *fieldValueCopy = mxDuplicateArray(fieldValue); mxSetFieldByNumber(pStruct, 0, fieldNumber, fieldValueCopy); free(name); }
int buffer_gethdr(int server, mxArray *plhs[], const mxArray *prhs[]) { int verbose = 0; int result = 0; message_t *request = NULL; message_t *response = NULL; /* this is for the Matlab specific output */ const char *field_names[NUMBER_OF_FIELDS] = {"nchans", "nsamples", "nevents", "fsample", "data_type", "bufsize"}; /* allocate the elements that will be used in the communication */ request = malloc(sizeof(message_t)); request->def = malloc(sizeof(messagedef_t)); request->buf = NULL; request->def->version = VERSION; request->def->command = GET_HDR; request->def->bufsize = 0; if (verbose) print_request(request->def); result = clientrequest(server, request, &response); if (result == 0) { if (verbose) print_response(response->def); if (response->def->command==GET_OK) { headerdef_t *headerdef = (headerdef_t *) response->buf; if (verbose) print_headerdef(headerdef); plhs[0] = mxCreateStructMatrix(1, 1, NUMBER_OF_FIELDS, field_names); mxSetFieldByNumber(plhs[0], 0, 0, mxCreateDoubleScalar((double)(headerdef->nchans))); mxSetFieldByNumber(plhs[0], 0, 1, mxCreateDoubleScalar((double)(headerdef->nsamples))); mxSetFieldByNumber(plhs[0], 0, 2, mxCreateDoubleScalar((double)(headerdef->nevents))); mxSetFieldByNumber(plhs[0], 0, 3, mxCreateDoubleScalar((double)(headerdef->fsample))); mxSetFieldByNumber(plhs[0], 0, 4, mxCreateDoubleScalar((double)(headerdef->data_type))); mxSetFieldByNumber(plhs[0], 0, 5, mxCreateDoubleScalar((double)(headerdef->bufsize))); addChunksToMatrix(plhs[0], (const char *) response->buf + sizeof(headerdef_t), headerdef->bufsize, headerdef->nchans); } else { result = response->def->command; } } if (response) { FREE(response->def); FREE(response->buf); FREE(response); } if (request) { FREE(request->def); FREE(request->buf); FREE(request); } return result; }
void cmex_object_list(int nlhs, mxArray *plhs[], /**< entlist */ int nrhs, const mxArray *prhs[] ) /**< () */ { OBJECT *obj; char criteria[1024]="(undefined)"; FINDPGM *search = NULL; char *fields[] = {"name","class","parent","flags","location","service","rank","clock","handle"}; FINDLIST *list = NULL; if (nrhs>0 && mxGetString(prhs[0],criteria,sizeof(criteria))!=0) output_error("gl('list',type='object'): unable to read search criteria (arg 2)"); else if (nrhs>0 && (search=find_mkpgm(criteria))==NULL) output_error("gl('list',type='object'): unable to run search '%s'",criteria); else if (search==NULL && (list=find_objects(NULL,NULL))==NULL) output_error("gl('list',type='object'): unable to obtain default list"); else if (list==NULL && (list=find_runpgm(NULL,search))==NULL) output_error("gl('list',type='object'): unable search failed"); else if ((plhs[0] = mxCreateStructMatrix(list->hit_count,1,sizeof(fields)/sizeof(fields[0]),fields))==NULL) output_error("gl('list',type='object'): unable to allocate memory for result list"); else { unsigned int n; for (n=0, obj=find_first(list); obj!=NULL; n++, obj=find_next(list,obj)) { char tmp[1024]; mxArray *data; double *pDouble; unsigned int *pInt; mxSetFieldByNumber(plhs[0], n, 0, mxCreateString(object_name(obj))); mxSetFieldByNumber(plhs[0], n, 1, mxCreateString(obj->oclass->name)); mxSetFieldByNumber(plhs[0], n, 2, mxCreateString(obj->parent?object_name(obj->parent):NONE)); mxSetFieldByNumber(plhs[0], n, 3, mxCreateString(convert_from_set(tmp,sizeof(tmp),&(obj->flags),object_flag_property())?tmp:ERROR)); pDouble = mxGetPr(data=mxCreateDoubleMatrix(1,2,mxREAL)); pDouble[0] = obj->longitude; pDouble[1] = obj->latitude; mxSetFieldByNumber(plhs[0], n, 4, data); pDouble = mxGetPr(data=mxCreateDoubleMatrix(1,2,mxREAL)); pDouble[0] = (double)obj->in_svc/TS_SECOND; pDouble[1] = (double)obj->out_svc/TS_SECOND; mxSetFieldByNumber(plhs[0], n, 5, data); pInt = (unsigned int*)mxGetPr(data=mxCreateNumericMatrix(1,1,mxINT32_CLASS,mxREAL)); pInt[0] = obj->rank; mxSetFieldByNumber(plhs[0], n, 6, data); pDouble = mxGetPr(data=mxCreateDoubleMatrix(1,1,mxREAL)); pDouble[0] = (double)obj->clock/TS_SECOND; mxSetFieldByNumber(plhs[0], n, 7, data); mxSetFieldByNumber(plhs[0], n, 8, make_handle(MH_OBJECT,obj)); } } }
void mexProblem::ObtainMxArrayFromElement(mxArray *&Xmx, const Element *X) { integer sizeoftempdata = X->GetSizeofTempData(); integer nfields = sizeoftempdata + 1; std::string *fnames = new std::string[nfields]; X->ObtainTempNames(fnames); fnames[sizeoftempdata].assign("main"); char **names = new char *[nfields]; for (integer i = 0; i < nfields; i++) { names[i] = new char[30]; if (fnames[i].size() >= 30) { mexErrMsgTxt("The lengths of field names should be less than 30!"); } strcpy(names[i], fnames[i].c_str()); } mxArray *tmp; const char *name; const SharedSpace *Sharedtmp; integer lengthtmp, inc = 1; const double *Sharedtmpptr; double *tmpptr; Xmx = mxCreateStructMatrix(1, 1, nfields, const_cast<const char **> (names)); for (integer i = 0; i < nfields; i++) { name = mxGetFieldNameByNumber(Xmx, i); if (strcmp(name, "main") != 0) { Sharedtmp = X->ObtainReadTempData(name); Sharedtmpptr = Sharedtmp->ObtainReadData(); lengthtmp = Sharedtmp->Getlength(); } else { Sharedtmpptr = X->ObtainReadData(); lengthtmp = X->Getlength(); } tmp = mxCreateDoubleMatrix(lengthtmp, 1, mxREAL); tmpptr = mxGetPr(tmp); dcopy_(&lengthtmp, const_cast<double *> (Sharedtmpptr), &inc, tmpptr, &inc); mxSetFieldByNumber(Xmx, 0, i, tmp); } for (integer i = 0; i < nfields; i++) delete[] names[i]; delete[] names; delete[] fnames; };
/** * storeString( ) - store the given string value in the * mxStruct structure in field named fieldName */ void storeString(mxArray *mxStruct, char *fieldName, char *value) { char msg[1025]; mxArray *fieldValue; int fieldNum = mxGetFieldNumber(mxStruct, fieldName); if (fieldNum < 0) { sprintf(msg,"Error: unknown field: (%s)\n", fieldName); mexErrMsgTxt(msg); } fieldValue = mxCreateString(value); mxSetFieldByNumber(mxStruct, 0, fieldNum, fieldValue); }