/* PsychAllocOutStructArray() -If argument is optional we allocate the structure even if the argument is not present. If this bothers you, then check within the subfunction for the presense of a return argument before creating the struct array. We allocate space regardeless of whether the argument is present because this is consistant with other "PsychAllocOut*" functions which behave this way because in some situations subfunctions might derive returned results from values stored in an optional argument. -If position is -1 then don't attempt to return the created structure to the calling environment. Instead just allocate the structure and return it in pStruct. This is how to create a structure which is embeded within another structure using PsychSetStructArrayStructArray(). Note that we use -1 as the flag and not NULL because NULL is 0 and 0 is reserved for future use as a reference to the subfunction name, of if none then the function name. */ boolean PsychAllocOutStructArray( int position, PsychArgRequirementType isRequired, int numElements, int numFields, const char **fieldNames, PsychGenericScriptType **pStruct) { mxArray **mxArrayOut; int structArrayNumDims=2; int structArrayDims[2]; PsychError matchError; Boolean putOut; structArrayDims[0]=1; structArrayDims[1]=numElements; if(position !=kPsychNoArgReturn){ //Return the result to both the C caller and the scripting environment. PsychSetReceivedArgDescriptor(position, PsychArgOut); PsychSetSpecifiedArgDescriptor(position, PsychArgOut, PsychArgType_structArray, isRequired, 1,1,numElements,numElements,0,0); *pStruct = mxCreateStructArray(structArrayNumDims, structArrayDims, numFields, fieldNames); matchError=PsychMatchDescriptors(); putOut=PsychAcceptOutputArgumentDecider(isRequired, matchError); if(putOut){ mxArrayOut = PsychGetOutArgMxPtr(position); *mxArrayOut=*pStruct; } return(putOut); }else{ //Return the result only to the C caller. Ignore "required". *pStruct = mxCreateStructArray(structArrayNumDims, structArrayDims, numFields, fieldNames); return(TRUE); } }
mxArray* make_matlab_nodes_struct(const CvDTreeNode *node) { ASSERT_NON_NULL(node); // Some values are stored regardless of whether the node is internal or external // regression value mxArray* double_val_mx = mxCreateDoubleScalar(node->value); ASSERT_NON_NULL(double_val_mx); // number of samples that reached this node mxArray* sample_count_mx = mxCreateDoubleScalar(node->sample_count); ASSERT_NON_NULL(sample_count_mx); if (node->left == NULL && node->right == NULL) { //leaf node mxArray* leaf_struct = mxCreateStructArray(num_dims, dims, leaf_node_ndims, leaf_node_field_names); ASSERT_NON_NULL(leaf_struct); mxSetField(leaf_struct, 0, "value", double_val_mx); mxSetField(leaf_struct, 0, "samples", sample_count_mx); return leaf_struct; } else { // internal node, so need to recurse mxArray* node_struct = mxCreateStructArray(num_dims, dims, internal_node_ndims, internal_node_field_names); ASSERT_NON_NULL(node_struct); mxSetField(node_struct, 0, "l", make_matlab_nodes_struct(node->left)); mxSetField(node_struct, 0, "r", make_matlab_nodes_struct(node->right)); mxSetField(node_struct, 0, "value", double_val_mx); mxSetField(node_struct, 0, "samples", sample_count_mx); return node_struct; } }
// From MT_AtomTypes_CPU to Matlab structure void f_ImSTEM2Matlab(int nThk, int nDet, int line, int nxs, int nys, sImSTEM *ImSTEM, mxArray *&mxImSTEM) { const char *field_names_ImSTEM[] = {"DetInt"}; int number_of_fields_ImSTEM = 1; mwSize dims_ImSTEM[2] = {nThk, 1}; const char *field_names_DetInt[] = {"Tot", "Coh"}; int number_of_fields_DetInt = 2; mwSize dims_DetInt[2] = {nDet, 1}; mxArray *mxDetInt; mxImSTEM = mxCreateStructArray(2, dims_ImSTEM, number_of_fields_ImSTEM, field_names_ImSTEM); for(int iThk = 0; iThk<nThk; iThk++) { mxDetInt = mxCreateStructArray(2, dims_DetInt, number_of_fields_DetInt, field_names_DetInt); mxSetField(mxImSTEM, iThk, "DetInt", mxDetInt); for(int iDet=0; iDet<nDet; iDet++) { if(line==1) { CreateSetValue2mxField(mxDetInt, iDet, "Tot", nxs, ImSTEM[iThk].DetInt[iDet].Tot); CreateSetValue2mxField(mxDetInt, iDet, "Coh", nxs, ImSTEM[iThk].DetInt[iDet].Coh); } else { CreateSetValue2mxField(mxDetInt, iDet, "Tot", nxs, nys, ImSTEM[iThk].DetInt[iDet].Tot); CreateSetValue2mxField(mxDetInt, iDet, "Coh", nxs, nys, ImSTEM[iThk].DetInt[iDet].Coh); } } } }
mxArray *rmat2mx(int m, int n, rmulti **A, int LDA) { const char *field_names[]={"prec","sign","exp","digits"}; mwSize dims[2]={m,n},scalar[2]={1,1},size[2]={1,1}; mxArray *ret=NULL,*value=NULL; int i,j,k; ret=mxCreateStructArray(2,dims,4,field_names); for(j=0; j<n; j++){ for(i=0; i<m; i++){ // prec value=mxCreateNumericArray(2,scalar,mxINT64_CLASS,mxREAL); (*(int64_t*)mxGetData(value))=MAT(A,i,j,LDA)->_mpfr_prec; mxSetField(ret,j*m+i,"prec",value); // sign value=mxCreateNumericArray(2,scalar,mxINT32_CLASS,mxREAL); (*(int32_t*)mxGetData(value))=MAT(A,i,j,LDA)->_mpfr_sign; mxSetField(ret,j*m+i,"sign",value); // exp value=mxCreateNumericArray(2,scalar,mxINT64_CLASS,mxREAL); (*(int64_t*)mxGetData(value))=MAT(A,i,j,LDA)->_mpfr_exp; mxSetField(ret,j*m+i,"exp",value); // digits size[1]=rget_size(MAT(A,i,j,LDA)); value=mxCreateNumericArray(2,size,mxUINT64_CLASS,mxREAL); for(k=0; k<size[1]; k++){ ((uint64_t*)mxGetData(value))[k]=MAT(A,i,j,LDA)->_mpfr_d[k]; } mxSetField(ret,j*m+i,"digits",value); } } return ret; }
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); // 方法二:效率較高 } }
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 ); } }
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; }
static void xcreate (mxArray *mnode, int i, VlHIKMNode *node) { int node_K = vl_ikm_get_K (node->filter) ; int M = vl_ikm_get_ndims (node->filter) ; vl_ikm_acc const *centers = vl_ikm_get_centers (node->filter) ; mxArray *mcenters ; mcenters = mxCreateNumericMatrix (M, node_K, mxINT32_CLASS, mxREAL); memcpy (mxGetPr(mcenters), centers, sizeof(vl_ikm_acc) * M * node_K) ; mxSetField (mnode, i, "centers", mcenters) ; if (node->children) { mxArray * msub ; const char * field_names[] = {"centers", "sub" } ; mwSize dims [2] ; int k ; dims[0] = 1 ; dims[1] = node_K ; msub = mxCreateStructArray (2, dims, 2, field_names) ; for (k = 0 ; k < node_K ; ++k) { xcreate (msub, k, node -> children [k]) ; } mxSetField (mnode, i, "sub", msub) ; } }
mxArray *GetTick(mxArray *inst, mxArray *start, mxArray *end) { mxArray *result; const char *field_names[] = {"tradingday", "time", "instrument", "o", "h", "l", "c", "v", "i", "a1", "b1", "av1", "bv1"}; string instrument = mxArrayToString(inst); int st = mxGetScalar(start); int et = mxGetScalar(end); auto_ptr<DBClientCursor> cursor; BSONObjBuilder b; BSONObjBuilder timePeriod; b.append("InstrumentID", instrument); timePeriod.appendDate("$gte",( (st - 719529) * 24LL)* 60LL * 60LL * 1000LL); timePeriod.appendDate("$lte", ( (et - 719529 + 1) * 24LL) * 60LL * 60LL * 1000LL); b.append("UpdateTime", timePeriod.obj()); BSONObj qry = b.obj(); cursor = mCon->query(string("MarketData.") + collection, qry); int size = cursor->itcount(); // mexPrintf("数据长度%d, collection为%s\n", size, collection.c_str()); mwSize dims[2] = {1, size}; result = mxCreateStructArray(2, dims, sizeof(field_names)/sizeof(*field_names), field_names); cursor = mCon->query(string("MarketData.") + collection, qry); BSONObj p; int i = size - 1; while(cursor->more()) { p = cursor->next(); tm buf; //trun into peking time; Date_t pkTime = Date_t(p["UpdateTime"].Date().millis + 8 * 3600000LL); double time = pkTime.millis%1000 / 100 / 100000.0; pkTime.toTm(&buf); int day = (buf.tm_year + 1900) * 10000 + (buf.tm_mon + 1) * 100 + buf.tm_mday; time = time + buf.tm_hour + buf.tm_min / 100.0 + buf.tm_sec / 10000.0; mxSetField(result, i, "tradingday", mxCreateDoubleScalar(day)); mxSetField(result, i, "time", mxCreateDoubleScalar(time)); mxSetField(result, i, "instrument", mxCreateString(instrument.c_str())); mxSetField(result, i, "o", mxCreateDoubleScalar( p["OpenPrice"].Double() )); mxSetField(result, i, "h", mxCreateDoubleScalar(p["HighestPrice"].Double())); mxSetField(result, i, "l", mxCreateDoubleScalar(p["LowestPrice"].Double())); mxSetField(result, i, "c", mxCreateDoubleScalar(p["LastPrice"].Double())); mxSetField(result, i, "v", mxCreateDoubleScalar(p["Volume"].Int())); mxSetField(result, i, "i", mxCreateDoubleScalar(p["OpenInterest"].Double())); mxSetField(result, i, "a1", mxCreateDoubleScalar(p["AskPrice1"].Double())); mxSetField(result, i, "b1", mxCreateDoubleScalar(p["BidPrice1"].Double())); mxSetField(result, i, "av1", mxCreateDoubleScalar(p["AskVolume1"].Int())); mxSetField(result, i, "bv1", mxCreateDoubleScalar(p["BidVolume1"].Int())); --i; if(i < -1) { mexWarnMsgTxt("GetTick程序越界!"); break; } } return result; }
void MatlabStructure::New(const MatlabProto& proto, int length) { int nf = proto.fields.size(); const char* fields[nf]; for (int i = 0; i < nf; i++) { fields[i] = proto.fields[i].c_str(); } mwSize size = length; Configure(proto, mxCreateStructArray(1, &size, nf, fields)); }
// This can potentially hold other bits of metadata but for now just has the nodes recursive // structure. mxArray* make_matlab_tree_struct(CvForestTree *tree) { ASSERT_NON_NULL(tree); mxArray* tree_struct = mxCreateStructArray(num_dims, dims, tree_num_fields, tree_field_names); ASSERT_NON_NULL(tree_struct); mxArray* num_leaves_mx = mxCreateDoubleScalar(num_leaves_in_subtree(tree->get_root())); ASSERT_NON_NULL(num_leaves_mx); mxSetField(tree_struct, 0, "num_leaves", num_leaves_mx); mxSetField(tree_struct, 0, "nodes", make_matlab_nodes_struct(tree->get_root())); return tree_struct; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { gpc_polygon subject, clip, result; mwSize dims[2], GPC_ARG; const char *field_names[] = {"x","y","hole"}; if (nrhs == 0) { mexPrintf("\nOutPol = PolygonClip(RefPol, ClipPol, [type]);\n\n"); mexPrintf("All polygons are structures with the fields ...\n"); mexPrintf(" .x: x-coordinates of contour\n"); mexPrintf(" .y: y-coordinates of contour\n"); mexPrintf(" .hole: hole flag\n"); mexPrintf("\nEvery polygon may contain several contours (s.example). Optional type parameter selects method:\n"); mexPrintf("0 - Diff\n"); mexPrintf("1 - And (Standard)\n"); mexPrintf("2 - Xor\n"); mexPrintf("3 - Union\n"); mexPrintf("\nPolygon Clipping Routine based on gpc2.32. Credit goes to ...\n"); mexPrintf("Alan Murta, Advanced Interfaces Group, Department of Computer Science, University of Manchester\n"); mexPrintf("http://www.cs.man.ac.uk/~toby/alan/software//\n\n"); return;} /* Check number of arguments */ if (nrhs < 2 || nrhs > 3) mexErrMsgTxt("Two or three inputs required."); if (nlhs != 1) mexErrMsgTxt("One output required."); /* Import polygons to structures */ gpc_read_polygon_MATLAB(prhs[0], &subject); gpc_read_polygon_MATLAB(prhs[1], &clip); /* Calling computational routine */ if (nrhs==2 || !mxIsDouble(prhs[2]) || mxGetM(prhs[2])!=1 || mxGetN(prhs[2])!=1) GPC_ARG = GPC_INT; else GPC_ARG = mxGetScalar(prhs[2]); if (GPC_ARG!=GPC_DIFF && GPC_ARG!=GPC_INT && GPC_ARG!=GPC_XOR && GPC_ARG!=GPC_UNION) GPC_ARG = GPC_INT; gpc_polygon_clip(GPC_ARG, &subject, &clip, &result); /* Output Data to Matlab */ dims[0] = 1; dims[1] = result.num_contours; plhs[0] = mxCreateStructArray(2, dims, 3, field_names); gpc_write_polygon_MATLAB(plhs[0], &result); }
mxArray * FT_set_H_MatrixPtr(const dd_MatrixPtr M) { mxArray * P; mxArray * tmpa; mxArray * tmpb; mxArray * tmpl; int i, j; double * a; double * b; double * l; int k=0; dd_rowrange ii; if ((M !=NULL) && (M->representation == dd_Inequality)) { const char *f[] = {"A", "B", "lin"}; int dims[] = {1}; P = mxCreateStructArray(1, dims, 3, f); if (set_card(M->linset)) { tmpl = mxCreateDoubleMatrix(1, set_card(M->linset), mxREAL); l = mxGetPr(tmpl); for (ii=1; ii<=M->rowsize; ii++) { if (set_member(ii, M->linset)) { l[k] = (int)ii; k ++; } } mxSetField(P, 0, "lin", tmpl); } tmpb = mxCreateDoubleMatrix(M->rowsize, 1, mxREAL); b = mxGetPr(tmpb); tmpa = mxCreateDoubleMatrix(M->rowsize, M->colsize - 1, mxREAL); a = mxGetPr(tmpa); for (i = 0 ; i < (int)(M->rowsize); i++) { b[i] = dd_get_d(M->matrix[i][0]); for (j = 0; j < (int)(M->colsize) - 1; j++) { a[i + j * (int)(M->rowsize)] = - dd_get_d(M->matrix[i][j + 1]); } } mxSetField(P, 0, "A", tmpa); mxSetField(P, 0, "B", tmpb); return P; } return 0; }
static mxArray* stats_mxArray(opnorm_stats_t stats) { const mwSize dims[] = {1}; const char* fields[] = {"neval", "nfifo", "fifomax", "nthread"}; mxArray *mxstats; if ((mxstats = mxCreateStructArray(1, dims, 4, fields)) == NULL) return NULL; mxSetField(mxstats, 0, "neval", uint64_mxArray(stats.neval)); mxSetField(mxstats, 0, "nfifo", uint64_mxArray(stats.nfifo)); mxSetField(mxstats, 0, "fifomax", uint64_mxArray(stats.fifomax)); mxSetField(mxstats, 0, "nthread", uint32_mxArray(stats.nthread)); return mxstats; }
mxArray * hikm_to_matlab (VlHIKMTree * tree) { int K = vl_hikm_get_K (tree) ; int depth = vl_hikm_get_depth (tree) ; mwSize dims [2] = {1, 1} ; mxArray *mtree ; const char *field_names[] = {"K", "depth", "centers", "sub"} ; /* Create the main struct array */ mtree = mxCreateStructArray (2, dims, NFIELDS(field_names), field_names) ; mxSetField (mtree, 0, "K", mxCreateDoubleScalar (K)) ; mxSetField (mtree, 0, "depth", mxCreateDoubleScalar (depth)) ; if (tree->root) xcreate (mtree, 0, tree->root) ; return mtree; }
mxArray* CLinearMapping::toMxArray() const { int dims[1]; dims[0]=1; mxArray* matlabArray; const char* fieldNames[]={"type", "W", "b", "numParams", "inputDim", "outputDim", "optimiser", "beta"}; matlabArray = mxCreateStructArray(1, dims, 8, fieldNames); mxSetField(matlabArray, 0, "type", convertMxArray("linear")); mxSetField(matlabArray, 0, "W", convertMxArray("W")); mxSetField(matlabArray, 0, "b", convertMxArray("b")); mxSetField(matlabArray, 0, "numParams", convertMxArray((double)getOptNumParams())); mxSetField(matlabArray, 0, "inputDim", convertMxArray((double)getInputDim())); mxSetField(matlabArray, 0, "outputDim", convertMxArray((double)getOutputDim())); mxSetField(matlabArray, 0, "optimiser", convertMxArray(getDefaultOptimiserStr())); mxSetField(matlabArray, 0, "beta", convertMxArray(variance)); return matlabArray; }
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); } }
/** * creates a matlab struct array from a vector of info objects */ mxArray *createInfoStructArray(vector<Info> &infov) { mwSize dims[2]; dims[0] = infov.size(); dims[1] = infov.size() == 0 ? 0 : 1; // create array mxArray *arr = mxCreateStructArray(2, dims, infoNumFields, (const char**) infoFieldNames); if(arr == NULL) { mexErrMsgTxt("couldn't create struct array."); return NULL; } // fill array unsigned int ind = 0; for(vector<Info>::iterator i = infov.begin(); i != infov.end(); i++, ind++) { setInfoFields(arr, ind, (*i)); } return arr; }
/* Examines the values at each leaf node in order to see what the distribution of data we put in is doing */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { ASSERT_NUM_RHS_ARGS_EQUALS(1); const mxArray* forest_ptr = prhs[0]; ASSERT_IS_POINTER(forest_ptr); CvRTrees *forest = (CvRTrees *) unpack_pointer(forest_ptr); // We are going to return a cell array with one cell per tree, so need this number int num_trees = forest->get_tree_count(); mexPrintf("Loaded forest of %d trees, retrieving leave node values.\n", num_trees); mxArray *output_cell_array = mxCreateCellMatrix(1, num_trees); ASSERT_NON_NULL(output_cell_array); for (unsigned int t = 0; t < num_trees; t++) { mxArray* tree_struct = mxCreateStructArray(num_dims, dims, tree_num_fields, tree_field_names); ASSERT_NON_NULL(tree_struct); mxSetCell(output_cell_array, t, make_matlab_tree_struct(forest->get_tree(t))); } plhs[0] = output_cell_array; }
void eng_make_Struct() { const char *name; int field_count; MLGetFunction(stdlink, &name, &field_count); std::vector<const char *> field_names(field_count); for (int i=0; i < field_count; ++i) { MLGetString(stdlink, &(field_names[i])); } int *handle_list; int handle_count; MLGetInteger32List(stdlink, &handle_list, &handle_count); int *mmDims; int depth; MLGetInteger32List(stdlink, &mmDims, &depth); std::vector<mwSize> mbDimsVec(depth); std::reverse_copy(mmDims, mmDims+depth, mbDimsVec.begin()); mwSize *mbDims = &mbDimsVec[0]; mxArray *var = mxCreateStructArray(depth, mbDims, field_count, &(field_names[0])); int len = handle_count / field_count; assert(mxGetNumberOfElements(var) == len); for (int i=0; i < len; ++i) for (int j=0; j < field_count; ++j) { mxSetFieldByNumber(var, i, j, handles.value(handle_list[i*len + j])); handles.remove(handle_list[i*len + j]); // remove to avoid double mxFree() } for (int i=0; i < field_count; ++i) MLReleaseString(stdlink, field_names[i]); MLReleaseInteger32List(stdlink, handle_list, handle_count); MLReleaseInteger32List(stdlink, mmDims, depth); returnHandle(var); }
inline void callFunction(mxArray* plhs[], const mxArray*prhs[],const int nlhs) { if (!mxIsCell(prhs[0])) mexErrMsgTxt("argument 2 should be a cell"); std::vector<NodeElem *> *gstruct = mexMatlabToCgroups(prhs[0]); mwSize dims[1] = {1}; const char *names[] = {"eta_g", "groups", "own_variables","N_own_variables"}; plhs[1]=mxCreateStructArray(1,dims,4,names); SpMatrix<bool> *groups; Vector<int> *own_variables; Vector<int> *N_own_variables; Vector<double> *eta_g; int *permutations; int nb_perm; int nb_vars = _treeOfGroupStruct<double>(gstruct,&permutations,&nb_perm,&eta_g,&groups,&own_variables,&N_own_variables); del_gstruct(gstruct); mxArray* mxeta_g = makeVector<double>(eta_g); mxArray* mxown_variables = makeVector<int>(own_variables); mxArray* mxN_own_variables = makeVector<int>(N_own_variables); mxArray* mxgroups[1]; convertSpMatrix<bool>(mxgroups[0],groups->m(),groups->n(),groups->n(), groups->nzmax(),groups->v(),groups->r(),groups->pB()); delete eta_g; delete groups; delete own_variables; delete N_own_variables; mxSetField(plhs[1],0,"eta_g",mxeta_g); mxSetField(plhs[1],0,"groups",mxgroups[0]); mxSetField(plhs[1],0,"own_variables",mxown_variables); mxSetField(plhs[1],0,"N_own_variables",mxN_own_variables); dims[0] = nb_perm; mxArray *mxperm = mxCreateNumericArray((mwSize)1,dims,mxINT32_CLASS,mxREAL); if(nb_perm > 0) memcpy(mxGetPr(mxperm),permutations,nb_perm * sizeof(int)); plhs[0] = mxperm; dims[0] = 1; plhs[2]=mxCreateNumericArray((mwSize)1,dims,mxINT32_CLASS,mxREAL); int* pr_out=reinterpret_cast<int *>(mxGetPr(plhs[2])); *pr_out = nb_vars; }
void set_structure(value_struct* structure, const mxArray* plhs[], int i, int numb_fields) { int k=0; char **field_names=malloc(sizeof(char*)*numb_fields); for (k=0;k<numb_fields;k++) { field_names[k]=malloc(sizeof(char)*(strlen(structure[k].name)+1)); field_names[k]=structure[k].name; } for (k=0;k<numb_fields;k++) { mwSize dim = 1; const mwSize dims[1]={1}; mxArray* valeur =mxCreateNumericArray(dim, dims,mxDOUBLE_CLASS,mxREAL); double* pointer = (double*)mxGetPr(valeur); pointer[0]=(double)structure[k].value; mexPrintf("%s=%e",structure[k].name,pointer[0]); plhs[i]=mxCreateStructArray(dim, dims, numb_fields, field_names); mxSetField(plhs[i],0,structure[k].name,valeur); } free(field_names); }
mxArray *Trader::GetOrder(int ind, string OrderRef) { if(ind < v_tds.size() && v_tds[ind] != NULL) { CThostFtdcOrderField order; if (TD_GetOrder(v_tds[ind], OrderRef.c_str(), &order)) { mxArray *result; const char *field_names[] = {"BrokerID", "InvestorID", "InstrumentID", "OrderRef", "UserID", "Direction", "CombOffsetFlag", "LimitPrice", "ExchangeID", "OrderSysID", "OrderStatus", "FrontID", "SessionID"}; mwSize dims[2] = {1, 1}; result = mxCreateStructArray(2, dims, sizeof(field_names)/sizeof(*field_names), field_names); string tmp; mxSetField(result, 0, "BrokerID", mxCreateString(order.BrokerID)); mxSetField(result, 0, "InvestorID", mxCreateString(order.InvestorID)); mxSetField(result, 0, "InstrumentID", mxCreateString(order.InstrumentID)); mxSetField(result, 0, "OrderRef", mxCreateString(order.OrderRef)); mxSetField(result, 0, "UserID", mxCreateString(order.UserID)); tmp = string("") + order.Direction; mxSetField(result, 0, "Direction", mxCreateString(tmp.c_str())); mxSetField(result, 0, "CombOffsetFlag", mxCreateString(order.CombOffsetFlag)); mxSetField(result, 0, "LimitPrice", mxCreateDoubleScalar(order.LimitPrice)); mxSetField(result, 0, "ExchangeID", mxCreateString(order.ExchangeID)); mxSetField(result, 0, "OrderSysID", mxCreateString(order.OrderSysID)); tmp = string("") + order.OrderStatus; mxSetField(result, 0, "OrderStatus", mxCreateString(tmp.c_str())); mxSetField(result, 0, "FrontID", mxCreateDoubleScalar(order.FrontID)); mxSetField(result, 0, "SessionID", mxCreateDoubleScalar(order.SessionID)); return result; } PrintLog(string(__FUNCTION__) + string("账户: ") + to_string(ind) + string(" 不存在订单: ") + OrderRef, "error"); return mxCreateDoubleScalar(0); } PrintLog(string(__FUNCTION__) + string("不存在账户: ") + to_string(ind), "error"); return mxCreateDoubleScalar(0); }
mxArray* sf_c1_VrSubsystem_get_post_codegen_info(void) { const char* fieldNames[] = { "exportedFunctionsUsedByThisChart", "exportedFunctionsChecksum" }; mwSize dims[2] = { 1, 1 }; mxArray* mxPostCodegenInfo = mxCreateStructArray(2, dims, sizeof(fieldNames)/ sizeof(fieldNames[0]), fieldNames); { mxArray* mxExportedFunctionsChecksum = mxCreateString(""); mwSize exp_dims[2] = { 0, 1 }; mxArray* mxExportedFunctionsUsedByThisChart = mxCreateCellArray(2, exp_dims); mxSetField(mxPostCodegenInfo, 0, "exportedFunctionsUsedByThisChart", mxExportedFunctionsUsedByThisChart); mxSetField(mxPostCodegenInfo, 0, "exportedFunctionsChecksum", mxExportedFunctionsChecksum); } return mxPostCodegenInfo; }
mxArray* CMlpMapping::toMxArray() const { int dims[1]; dims[0]=1; mxArray* matlabArray; const char* fieldNames[]={"type", "nin", "nhidden", "nout", "nwts", "outfn", "w1", "b1", "w2", "b2", "numParams", "hiddenDim", "inputDim", "outputDim", "optimiser"}; matlabArray = mxCreateStructArray(1, dims, 15, fieldNames); mxSetField(matlabArray, 0, "type", convertMxArray("mlp")); mxSetField(matlabArray, 0, "nin", convertMxArray((double)getInputDim())); mxSetField(matlabArray, 0, "nhidden", convertMxArray((double)hiddenDim)); mxSetField(matlabArray, 0, "nout", convertMxArray((double)getOutputDim())); mxSetField(matlabArray, 0, "nwts", convertMxArray((double)getOptNumParams())); mxSetField(matlabArray, 0, "outfn", convertMxArray("linear")); mxSetField(matlabArray, 0, "w1", convertMxArray("W1")); mxSetField(matlabArray, 0, "b1", convertMxArray("b1")); mxSetField(matlabArray, 0, "w2", convertMxArray("W2")); mxSetField(matlabArray, 0, "b2", convertMxArray("b2")); mxSetField(matlabArray, 0, "numParams", convertMxArray((double)getOptNumParams())); mxSetField(matlabArray, 0, "hiddenDim", convertMxArray((double)hiddenDim)); mxSetField(matlabArray, 0, "inputDim", convertMxArray((double)getInputDim())); mxSetField(matlabArray, 0, "outputDim", convertMxArray((double)getOutputDim())); mxSetField(matlabArray, 0, "optimiser", convertMxArray(getDefaultOptimiserStr())); return matlabArray; }
void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) { double C, TolRel, TolAbs, QPBound, trn_err, MaxTime; double *vec_C; double *ptr; uint32_t num_of_Cs; uint32_t i, j, BufSize; uint16_t Method; int verb; ocas_return_value_T ocas; /* timing variables */ double init_time; double total_time; total_time = get_time(); init_time = total_time; if(nrhs < 1) mexErrMsgTxt("Improper number of input arguments."); /* get input arguments */ if(mxIsChar(prhs[0]) == false) { /* [W,W0,stat] = svmocas_mex(X,X0,y,C,Method,TolRel,TolAbs,QPBound,BufSize,nData,MaxTime); */ if(nrhs < 4 || nrhs > 12) mexErrMsgTxt("Improper number of input arguments."); if(nrhs >= 12) verb = (int)mxGetScalar(prhs[11]); else verb = DEFAULT_VERB; data_X = (mxArray*)prhs[0]; if (!(mxIsDouble(data_X))) mexErrMsgTxt("Input argument X must be of type double."); if (mxGetNumberOfDimensions(data_X) != 2) mexErrMsgTxt("Input argument X must be two dimensional"); X0 = mxGetScalar(prhs[1]); data_y = (double*)mxGetPr(prhs[2]); if(LIBOCAS_MAX(mxGetM(prhs[2]),mxGetN(prhs[2])) != mxGetN(prhs[0])) mexErrMsgTxt("Length of vector y must equl to the number of columns of matrix X."); nDim = mxGetM(prhs[0]); if(verb) { mexPrintf("Input data statistics:\n" " # of examples : %d\n" " dimensionality : %d\n", mxGetN(data_X), nDim); if( mxIsSparse(data_X)== true ) mexPrintf(" density : %.2f%%\n", 100.0*(double)mxGetNzmax(data_X)/((double)nDim*(double)(mxGetN(data_X)))); else mexPrintf(" density : 100%% (full)\n"); } num_of_Cs = LIBOCAS_MAX(mxGetN(prhs[3]),mxGetM(prhs[3])); if(num_of_Cs == 1) { C = (double)mxGetScalar(prhs[3]); } else { vec_C = (double*)mxGetPr(prhs[3]); } if(nrhs >= 5) Method = (uint32_t)mxGetScalar(prhs[4]); else Method = DEFAULT_METHOD; if(nrhs >= 6) TolRel = (double)mxGetScalar(prhs[5]); else TolRel = DEFAULT_TOLREL; if(nrhs >= 7) TolAbs = (double)mxGetScalar(prhs[6]); else TolAbs = DEFAULT_TOLABS; if(nrhs >= 8) QPBound = (double)mxGetScalar(prhs[7]); else QPBound = DEFAULT_QPVALUE; if(nrhs >= 9) BufSize = (uint32_t)mxGetScalar(prhs[8]); else BufSize = DEFAULT_BUFSIZE; if(nrhs >= 10 && mxIsInf(mxGetScalar(prhs[9])) == false) nData = (uint32_t)mxGetScalar(prhs[9]); else nData = mxGetN(data_X); if(nData < 1 || nData > mxGetN(prhs[0])) mexErrMsgTxt("Improper value of argument nData."); if(num_of_Cs > 1 && num_of_Cs < nData) mexErrMsgTxt("Length of the vector C less than the number of examples."); if(nrhs >= 11) MaxTime = (double)mxGetScalar(prhs[10]); else MaxTime = DEFAULT_MAXTIME; } else { /* [W,W0,stat] = svmocas_mex(svmlight_data_file,X0,C,Method,TolRel,TolAbs,QPBound,BufSize,nData,MaxTime); */ char *fname; int fname_len; if(nrhs < 3 || nrhs > 11) mexErrMsgTxt("Improper number of input arguments."); if(nrhs >= 11) verb = (int)mxGetScalar(prhs[10]); else verb = DEFAULT_VERB; if(!mxIsChar(prhs[0])) mexErrMsgTxt("First input argument must be of type string."); fname_len = mxGetNumberOfElements(prhs[0]) + 1; fname = mxCalloc(fname_len, sizeof(char)); if (mxGetString(prhs[0], fname, fname_len) != 0) mexErrMsgTxt("Could not convert first input argument to string."); if( load_svmlight_file(fname,verb) == -1 || data_X == NULL || data_y == NULL) mexErrMsgTxt("Cannot load input file."); nDim = mxGetM(data_X); X0 = mxGetScalar(prhs[1]); /* C = (double)mxGetScalar(prhs[2]);*/ num_of_Cs = LIBOCAS_MAX(mxGetN(prhs[2]),mxGetM(prhs[2])); if(num_of_Cs == 1) { C = (double)mxGetScalar(prhs[2]); } else { vec_C = (double*)mxGetPr(prhs[2]); } if(verb) mexPrintf("Input data statistics:\n" " # of examples : %d\n" " dimensionality : %d\n" " density : %.2f%%\n", mxGetN(data_X), nDim, 100.0*(double)mxGetNzmax(data_X)/((double)nDim*(double)(mxGetN(data_X)))); if(nrhs >= 4) Method = (uint32_t)mxGetScalar(prhs[3]); else Method = DEFAULT_METHOD; if(nrhs >= 5) TolRel = (double)mxGetScalar(prhs[4]); else TolRel = DEFAULT_TOLREL; if(nrhs >= 6) TolAbs = (double)mxGetScalar(prhs[5]); else TolAbs = DEFAULT_TOLABS; if(nrhs >= 7) QPBound = (double)mxGetScalar(prhs[6]); else QPBound = DEFAULT_QPVALUE; if(nrhs >= 8) BufSize = (uint32_t)mxGetScalar(prhs[7]); else BufSize = DEFAULT_BUFSIZE; if(nrhs >= 9 && mxIsInf(mxGetScalar(prhs[8])) == false) nData = (uint32_t)mxGetScalar(prhs[8]); else nData = mxGetN(data_X); if(nData < 1 || nData > mxGetN(data_X)) mexErrMsgTxt("Improper value of argument nData."); if(num_of_Cs > 1 && num_of_Cs < nData) mexErrMsgTxt("Length of the vector C less than the number of examples."); if(nrhs >= 10) MaxTime = (double)mxGetScalar(prhs[9]); else MaxTime = DEFAULT_MAXTIME; } /*---------------------------------------------------------------- Print setting -------------------------------------------------------------------*/ if(verb) { mexPrintf("Setting:\n"); if( num_of_Cs == 1) mexPrintf(" C : %f\n", C); else mexPrintf(" C : different for each example\n"); mexPrintf(" bias : %.0f\n" " # of examples : %d\n" " solver : %d\n" " cache size : %d\n" " TolAbs : %f\n" " TolRel : %f\n" " QPValue : %f\n" " MaxTime : %f [s]\n" " verb : %d\n", X0, nData, Method,BufSize,TolAbs,TolRel, QPBound, MaxTime, verb); } /* learned weight vector */ plhs[0] = (mxArray*)mxCreateDoubleMatrix(nDim,1,mxREAL); W = (double*)mxGetPr(plhs[0]); if(W == NULL) mexErrMsgTxt("Not enough memory for vector W."); oldW = (double*)mxCalloc(nDim,sizeof(double)); if(oldW == NULL) mexErrMsgTxt("Not enough memory for vector oldW."); W0 = 0; oldW0 = 0; A0 = mxCalloc(BufSize,sizeof(A0[0])); if(A0 == NULL) mexErrMsgTxt("Not enough memory for vector A0."); /* allocate buffer for computing cutting plane */ new_a = (double*)mxCalloc(nDim,sizeof(double)); if(new_a == NULL) mexErrMsgTxt("Not enough memory for auxciliary cutting plane buffer new_a."); if(num_of_Cs > 1) { for(i=0; i < nData; i++) data_y[i] = data_y[i]*vec_C[i]; } if( mxIsSparse(data_X)== true ) { /* for i=1:nData, X(:,i) = X(:,i)*y(i); end*/ for(i=0; i < nData; i++) mul_sparse_col(data_y[i], data_X, i); /* init cutting plane buffer */ sparse_A.nz_dims = mxCalloc(BufSize,sizeof(uint32_t)); sparse_A.index = mxCalloc(BufSize,sizeof(sparse_A.index[0])); sparse_A.value = mxCalloc(BufSize,sizeof(sparse_A.value[0])); if(sparse_A.nz_dims == NULL || sparse_A.index == NULL || sparse_A.value == NULL) mexErrMsgTxt("Not enough memory for cutting plane buffer sparse_A."); init_time=get_time()-init_time; if(verb) { mexPrintf("Starting optimization:\n"); if(num_of_Cs == 1) { ocas = svm_ocas_solver( C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &sparse_compute_W, &sparse_update_W, &sparse_add_new_cut, &sparse_compute_output, &qsort_data, &ocas_print, 0); } else { ocas = svm_ocas_solver_difC( vec_C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &sparse_compute_W, &sparse_update_W, &sparse_add_new_cut, &sparse_compute_output, &qsort_data, &ocas_print, 0); } } else { if(num_of_Cs == 1) { ocas = svm_ocas_solver( C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &sparse_compute_W, &sparse_update_W, &sparse_add_new_cut, &sparse_compute_output, &qsort_data, &ocas_print_null, 0); } else { ocas = svm_ocas_solver_difC( vec_C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &sparse_compute_W, &sparse_update_W, &sparse_add_new_cut, &sparse_compute_output, &qsort_data, &ocas_print_null, 0); } } } else { ptr = mxGetPr(data_X); for(i=0; i < nData; i++) { for(j=0; j < nDim; j++ ) { ptr[LIBOCAS_INDEX(j,i,nDim)] = ptr[LIBOCAS_INDEX(j,i,nDim)]*data_y[i]; } } /* init cutting plane buffer */ full_A = mxCalloc(BufSize*nDim,sizeof(double)); if( full_A == NULL ) mexErrMsgTxt("Not enough memory for cutting plane buffer full_A."); init_time=get_time()-init_time; if(verb) { mexPrintf("Starting optimization:\n"); if(num_of_Cs == 1) ocas = svm_ocas_solver( C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &full_compute_W, &full_update_W, &full_add_new_cut, &full_compute_output, &qsort_data, &ocas_print, 0); else ocas = svm_ocas_solver_difC( vec_C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &full_compute_W, &full_update_W, &full_add_new_cut, &full_compute_output, &qsort_data, &ocas_print, 0); } else { if(num_of_Cs == 1) ocas = svm_ocas_solver( C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &full_compute_W, &full_update_W, &full_add_new_cut, &full_compute_output, &qsort_data, &ocas_print_null, 0); else ocas = svm_ocas_solver_difC( vec_C, nData, TolRel, TolAbs, QPBound, MaxTime,BufSize, Method, &full_compute_W, &full_update_W, &full_add_new_cut, &full_compute_output, &qsort_data, &ocas_print_null, 0); } } if(verb) { mexPrintf("Stopping condition: "); switch( ocas.exitflag ) { case 1: mexPrintf("1-Q_D/Q_P <= TolRel(=%f) satisfied.\n", TolRel); break; case 2: mexPrintf("Q_P-Q_D <= TolAbs(=%f) satisfied.\n", TolAbs); break; case 3: mexPrintf("Q_P <= QPBound(=%f) satisfied.\n", QPBound); break; case 4: mexPrintf("Optimization time (=%f) >= MaxTime(=%f).\n", ocas.ocas_time, MaxTime); break; case -1: mexPrintf("Has not converged!\n" ); break; case -2: mexPrintf("Not enough memory for the solver.\n" ); break; } } total_time=get_time()-total_time; if(verb) { mexPrintf("Timing statistics:\n" " init_time : %f[s]\n" " qp_solver_time : %f[s]\n" " sort_time : %f[s]\n" " output_time : %f[s]\n" " add_time : %f[s]\n" " w_time : %f[s]\n" " print_time : %f[s]\n" " ocas_time : %f[s]\n" " total_time : %f[s]\n", init_time, ocas.qp_solver_time, ocas.sort_time, ocas.output_time, ocas.add_time, ocas.w_time, ocas.print_time, ocas.ocas_time, total_time); mexPrintf("Training error: %.4f%%\n", 100*(double)ocas.trn_err/(double)nData); } /* multiply data ba labels as it was at the begining */ if( mxIsSparse(data_X)== true ) { /* for i=1:nData, X(:,i) = X(:,i)*y(i); end*/ for(i=0; i < nData; i++) { mul_sparse_col(1/data_y[i], data_X, i); } } else { ptr = mxGetPr(data_X); for(i=0; i < nData; i++) { for(j=0; j < nDim; j++ ) { ptr[LIBOCAS_INDEX(j,i,nDim)] = ptr[LIBOCAS_INDEX(j,i,nDim)]/data_y[i]; } } } if(num_of_Cs > 1) { for(i=0; i < nData; i++) data_y[i] = data_y[i]/vec_C[i]; } plhs[1] = mxCreateDoubleScalar( W0 ); /* return ocas optimizer statistics */ /* typedef struct { uint32_t nIter; uint32_t nCutPlanes; double trn_err; double Q_P; double Q_D; double output_time; double sort_time; double solver_time; int8_t exitflag; } ocas_return_value_T; */ const char *field_names[] = {"nTrnErrors","Q_P","Q_D","nIter","nCutPlanes","exitflag", "init_time","output_time","sort_time","qp_solver_time","add_time", "w_time","print_time","ocas_time","total_time"}; mwSize dims[2] = {1,1}; plhs[2] = mxCreateStructArray(2, dims, (sizeof(field_names)/sizeof(*field_names)), field_names); mxSetField(plhs[2],0,"nIter",mxCreateDoubleScalar((double)ocas.nIter)); mxSetField(plhs[2],0,"nCutPlanes",mxCreateDoubleScalar((double)ocas.nCutPlanes)); mxSetField(plhs[2],0,"nTrnErrors",mxCreateDoubleScalar(ocas.trn_err)); mxSetField(plhs[2],0,"Q_P",mxCreateDoubleScalar(ocas.Q_P)); mxSetField(plhs[2],0,"Q_D",mxCreateDoubleScalar(ocas.Q_D)); mxSetField(plhs[2],0,"init_time",mxCreateDoubleScalar(init_time)); mxSetField(plhs[2],0,"output_time",mxCreateDoubleScalar(ocas.output_time)); mxSetField(plhs[2],0,"sort_time",mxCreateDoubleScalar(ocas.sort_time)); mxSetField(plhs[2],0,"qp_solver_time",mxCreateDoubleScalar(ocas.qp_solver_time)); mxSetField(plhs[2],0,"add_time",mxCreateDoubleScalar(ocas.add_time)); mxSetField(plhs[2],0,"w_time",mxCreateDoubleScalar(ocas.w_time)); mxSetField(plhs[2],0,"print_time",mxCreateDoubleScalar(ocas.print_time)); mxSetField(plhs[2],0,"ocas_time",mxCreateDoubleScalar(ocas.ocas_time)); mxSetField(plhs[2],0,"total_time",mxCreateDoubleScalar(total_time)); mxSetField(plhs[2],0,"exitflag",mxCreateDoubleScalar((double)ocas.exitflag)); return; }
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { int dims[2] = {1, 1 }; int i, buflen, status; char *filename; DYN_GROUP *dg; FILE *fp; int newentry; char *newname = NULL, *suffix; char tempname[128]; char message[256]; char **field_names; mxArray *field_value; /* Check for proper number of input and output arguments */ if (nrhs !=1) { mexErrMsgTxt("usage: dgz_read filename"); } if(nlhs > 1){ mexErrMsgTxt("Too many output arguments."); } buflen = (mxGetM(FILE_IN) * mxGetN(FILE_IN)) + 1; filename = mxCalloc(buflen, sizeof(char)); status = mxGetString(FILE_IN, filename, buflen); /* No need to uncompress a .dg file */ if ((suffix = strrchr(filename, '.')) && strstr(suffix, "dg") && !strstr(suffix, "dgz")) { fp = fopen(filename, "rb"); if (!fp) { sprintf(message, "Error opening data file \"%s\".", filename); mexErrMsgTxt(message); tempname[0] = 0; } } else if ((fp = uncompress_file(filename, tempname)) == NULL) { char fullname[128]; sprintf(fullname,"%s.dg", filename); mexPrintf(message); if ((fp = uncompress_file(fullname, tempname)) == NULL) { sprintf(fullname,"%s.dgz", filename); if ((fp = uncompress_file(fullname, tempname)) == NULL) { sprintf(message, "dg_read: file %s not found", filename); mexErrMsgTxt(message); } } } if (!(dg = dfuCreateDynGroup(4))) { mexErrMsgTxt("Error creating dyn group."); } if (!dguFileToStruct(fp, dg)) { /* THE PROBLEM */ sprintf(message, "dg_read: file %s not recognized as dg format", filename); fclose(fp); if (tempname[0]) unlink(tempname); mexErrMsgTxt(message); } fclose(fp); if (tempname[0]) unlink(tempname); dims[1] = 1; /* 10-August-2000 // Yusuke MURAYAMA modified below to add dgzfilename */ #ifdef YM_MODIFY field_names = mxCalloc(DYN_GROUP_NLISTS(dg)+1, sizeof (char *)); for (i = 0; i < DYN_GROUP_NLISTS(dg); i++) { field_names[i] = DYN_LIST_NAME(DYN_GROUP_LIST(dg,i)); } field_names[i] = "filename"; plhs[0] = mxCreateStructArray(2, (const mwSize*)dims, DYN_GROUP_NLISTS(dg)+1, (const char**)field_names); for (i = 0; i < DYN_GROUP_NLISTS(dg); i++) { field_value = dynListToCellArray(DYN_GROUP_LIST(dg, i)); if (!field_value) { sprintf(message, "dg_read: error reading data file \"%s\"", filename); dfuFreeDynGroup(dg); mexErrMsgTxt(message); } mxSetFieldByNumber(plhs[0], 0, i, field_value); } mxSetFieldByNumber(plhs[0], 0, i, mxCreateString(filename)); #else field_names = mxCalloc(DYN_GROUP_NLISTS(dg), sizeof (char *)); for (i = 0; i < DYN_GROUP_NLISTS(dg); i++) { field_names[i] = DYN_LIST_NAME(DYN_GROUP_LIST(dg,i)); } plhs[0] = mxCreateStructArray(2, dims, DYN_GROUP_NLISTS(dg), field_names); for (i = 0; i < DYN_GROUP_NLISTS(dg); i++) { field_value = dynListToCellArray(DYN_GROUP_LIST(dg, i)); if (!field_value) { sprintf(message, "dg_read: error reading data file \"%s\"", filename); dfuFreeDynGroup(dg); mexErrMsgTxt(message); } mxSetFieldByNumber(plhs[0], 0, i, field_value); } #endif dfuFreeDynGroup(dg); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { bool isError; thread_policy_flavor_t flavorConstant; int flavorPolicySize, flavorPolicySizeBytes, kernError; task_t threadID; thread_policy_t threadPolicy; mach_msg_type_number_t policySizeFilled; boolean_t isDefault, getDefault; char commandString[COMMAND_STRING_LENGTH]; // for return structure // ...outer const char *outerNames[] = {"threadID", "flavor", "policy", "policySize", "policyFillSize", "getDefault", "isDefault"}; int numOuterDims=2, numOuterFields=7; int outerDims[2]={1,1}; // ...inner const char *standardNames[] = {"no_data"}; int numInnerFieldsStandard= 1; /* const char *extendedNames[] = {"timeshare"}; int numInnerFieldsExtended= 1; */ const char *timeConstraintNames[]= {"period", "computation", "constraint", "preemptible"}; int numInnerFieldsTimeConstraint= 4; const char *precedenceNames[]= {"imporantance"}; int numInnerFieldsPrecedence= 1; int numInnerDims=2; int innerDims[2]={1,1}; // ...both mxArray *tempFieldValue, *innerStruct, *outerStruct; //get the policy flavor constant specified by the user and the getDefault argument if(nrhs<2 || nrhs > 2) mexErrMsgTxt("MachGetPriorityMex requires two input arguments. See help MachGetPriorityMex."); if(!mxIsChar(prhs[0])) mexErrMsgTxt("First input argument is not a string. See help MachGetPriorityMex."); mxGetString(prhs[0], commandString, COMMAND_STRING_LENGTH); isError=GetFlavorConstantFromFlavorString(commandString, mxGetM(prhs[0]) * mxGetN(prhs[0]), &flavorConstant); //case sensitive. if(isError) mexErrMsgTxt("Unrecognized command. See help MachGetPriorityMex."); if(!(mxIsDouble(prhs[1]) || mxIsLogical(prhs[1])) || mxGetN(prhs[1]) * mxGetM(prhs[1]) != 1) mexErrMsgTxt("Second argument must be 1x1 logical or double value. See help MachGetPriorityMex."); if(mxIsLogical(prhs[1])) getDefault= (boolean_t)mxGetLogicals(prhs[1])[0]; if(mxIsDouble(prhs[1])) getDefault= (boolean_t)mxGetPr(prhs[1])[0]; //read the priority settings switch(flavorConstant){ case THREAD_STANDARD_POLICY: flavorPolicySizeBytes=sizeof(thread_standard_policy_data_t); flavorPolicySize=THREAD_STANDARD_POLICY_COUNT; break; case THREAD_TIME_CONSTRAINT_POLICY: flavorPolicySizeBytes=sizeof(thread_time_constraint_policy_data_t); flavorPolicySize=THREAD_TIME_CONSTRAINT_POLICY_COUNT; break; case THREAD_PRECEDENCE_POLICY: flavorPolicySizeBytes=sizeof(thread_precedence_policy_data_t); flavorPolicySize=THREAD_PRECEDENCE_POLICY_COUNT; break; } threadPolicy=(thread_policy_t)malloc(flavorPolicySizeBytes); threadID= mach_thread_self(); policySizeFilled=flavorPolicySize; isDefault=getDefault; kernError=thread_policy_get(threadID, flavorConstant, threadPolicy, &policySizeFilled, &isDefault); //create and populate the return structure outerStruct= mxCreateStructArray(numOuterDims, outerDims, numOuterFields, outerNames); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]=(double)threadID; mxSetField(outerStruct, 0, "threadID", tempFieldValue); tempFieldValue= mxCreateString(commandString); mxSetField(outerStruct, 0, "flavor", tempFieldValue); switch(flavorConstant){ case THREAD_STANDARD_POLICY: innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsStandard, standardNames); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]= (double)((thread_standard_policy_t)threadPolicy)->no_data; mxSetField(innerStruct, 0, "no_data", tempFieldValue); break; /* THREAD_EXTENDED_POLICY is equal to THREAD_STANDARD_POLICY. Also, THREAD_EXTENDED_POLICY is undocumented. So we ignore it. case THREAD_EXTENDED_POLICY: innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsExtended, extendedNames); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]= (double)((thread_extended_policy_t)threadPolicy)->timeshare; mxSetField(innerStruct, 1, "timeshare", tempFieldValue); break; */ case THREAD_TIME_CONSTRAINT_POLICY: innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsTimeConstraint, timeConstraintNames); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->period; mxSetField(innerStruct, 0, "period", tempFieldValue); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->computation; mxSetField(innerStruct, 0, "computation", tempFieldValue); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->constraint; mxSetField(innerStruct, 0, "constraint", tempFieldValue); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->preemptible; mxSetField(innerStruct, 0, "preemptible", tempFieldValue); break; case THREAD_PRECEDENCE_POLICY: innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsPrecedence, precedenceNames); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]= (double)((thread_precedence_policy_t)threadPolicy)->importance; mxSetField(innerStruct, 0, "imporantance", tempFieldValue); break; } mxSetField(outerStruct,0, "policy", innerStruct); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]=flavorPolicySize; mxSetField(outerStruct, 0, "policySize", tempFieldValue); tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL); mxGetPr(tempFieldValue)[0]=policySizeFilled; mxSetField(outerStruct, 0, "policyFillSize", tempFieldValue); tempFieldValue= mxCreateLogicalMatrix(1, 1); mxGetLogicals(tempFieldValue)[0]=(bool)getDefault; mxSetField(outerStruct, 0, "getDefault", tempFieldValue); tempFieldValue= mxCreateLogicalMatrix(1, 1); mxGetLogicals(tempFieldValue)[0]=(bool)isDefault; mxSetField(outerStruct, 0, "isDefault", tempFieldValue); plhs[0]=outerStruct; free((void*)threadPolicy); }
/* * This ist the Entry Function of this Mex-DLL */ void mexFunction(int nlhs, mxArray*plhs[], int nrhs, const mxArray*prhs[]) { mexAtExit(CloseDBs); /* * Get the current Language */ if (Language == -1) { #ifdef _WIN32 switch(PRIMARYLANGID(GetUserDefaultLangID())) { case LANG_GERMAN: Language = 1; break; default: Language = 0; } #else Language = 0; #endif } /* * Print Version Information */ if (! FirstStart) { FirstStart = true; mexPrintf (MSG_HELLO, sqlite3_libversion()); } /* * Check if the first argument is a number, then we have to use * this number as an database id. */ int db_id = 0; int FirstArg = 0; int NumArgs = nrhs; if (nrhs >= 1 && mxIsNumeric(prhs[0])) { db_id = (int) *mxGetPr(prhs[0]); if (db_id < 0 || db_id > MaxNumOfDbs) { mexPrintf(MSG_INVALIDDBHANDLE); mexErrMsgTxt(MSG_IMPOSSIBLE); } db_id --; FirstArg ++; NumArgs --; } /* * All remaining arguments have to be strings */ bool isNotOK = false; int i; for (i = FirstArg; i < nrhs; i++) { if (! mxIsChar(prhs[i])) { isNotOK = true; break; } } if (NumArgs < 1 || isNotOK) { mexPrintf(MSG_USAGE); mexErrMsgTxt(MSG_INVALIDARG); } /* * Get the first string argument, this is the command string */ char *command = getstring(prhs[FirstArg]); if (! strcmp(command, "open")) { /* * open a database. There have to be two string arguments. * The command 'open' and the database filename */ if (NumArgs != 2) { mexPrintf(MSG_NOOPENARG, mexFunctionName()); mxFree(command); mexErrMsgTxt(MSG_INVALIDARG); } // TODO: Memoryleak 'command not freed' when getstring fails char* dbname = getstring(prhs[FirstArg +1]); /* * Is there an database ID? The close the database with the same id */ if (db_id > 0 && g_dbs[db_id]) { sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; } /* * If there isn't an database id, then try to get one */ if (db_id < 0) { for (i = 0; i < MaxNumOfDbs; i++) { if (g_dbs[i] == 0) { db_id = i; break; } } } /* * no database id? sorry, database id table full */ if (db_id < 0) { plhs[0] = mxCreateScalarDouble((double) 0); mexPrintf(MSG_NOFREESLOT); mxFree(command); mxFree(dbname); mexErrMsgTxt(MSG_IMPOSSIBLE); } /* * Open the database */ int rc = sqlite3_open(dbname, &g_dbs[db_id]); if (rc) { /* * Anything wrong? free the database id and inform the user */ mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id])); sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; plhs[0] = mxCreateScalarDouble((double) 0); mxFree(command); mxFree(dbname); mexErrMsgTxt(MSG_IMPOSSIBLE); } /* * return value will be the used database id */ plhs[0] = mxCreateScalarDouble((double) db_id +1); mxFree(dbname); } else if (! strcmp(command, "close")) { /* * close a database */ /* * if the database id is < 0 than close all open databases */ if (db_id < 0) { for (i = 0; i < MaxNumOfDbs; i++) { if (g_dbs[i]) { sqlite3_close(g_dbs[i]); g_dbs[i] = 0; } } } else { /* * If the database is open, then close it. Otherwise * inform the user */ if (! g_dbs[db_id]) { mxFree(command); mexErrMsgTxt(MSG_DBNOTOPEN); } else { sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; } } } else if (! strcmp(command, "status")) { for (i = 0; i < MaxNumOfDbs; i++) { mexPrintf("DB Handle %d: %s\n", i, g_dbs[i] ? "OPEN" : "CLOSED"); } } else { /* * Every unknown command is treated as an sql query string */ /* * database id < 0? Thats an error... */ if (db_id < 0) { mexPrintf(MSG_INVALIDDBHANDLE); mxFree(command); mexErrMsgTxt(MSG_IMPOSSIBLE); } /* * database not open? -> error */ if (!g_dbs[db_id]) { mxFree(command); mexErrMsgTxt(MSG_DBNOTOPEN); } const char* query = command; /* * emulate the "show tables" sql query */ if (! strcmpi(query, "show tables")) { query = "SELECT name as tablename FROM sqlite_master " "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' " "UNION ALL " "SELECT name as tablename FROM sqlite_temp_master " "WHERE type IN ('table','view') " "ORDER BY 1"; } /* * complete the query */ if (sqlite3_complete(query)) { mxFree(command); mexErrMsgTxt(MSG_INVQUERY); } sqlite3_stmt *st; /* * and prepare it * if anything is wrong with the query, than complain about it. */ if (sqlite3_prepare_v2(g_dbs[db_id], query, -1, &st, 0)) { if (st) sqlite3_finalize(st); mxFree(command); mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id])); } /* * Any results? */ int ncol = sqlite3_column_count(st); if (ncol > 0) { char **fieldnames = new char *[ncol]; /* Column names */ Values* allrows = 0; /* All query results */ Values* lastrow = 0; /* pointer to the last result row */ int rowcount = 0; /* number of result rows */ /* * Get the column names of the result set */ for(i=0; i<ncol; i++) { const char *cname = sqlite3_column_name(st, i); fieldnames[i] = new char [strlen(cname) +1]; strcpy (fieldnames[i], cname); /* * replace invalid chars by '_', so we can build * valid MATLAB structs */ char *mk_c = fieldnames[i]; while (*mk_c) { if ((*mk_c == ' ') || (*mk_c == '*') || (*mk_c == '?')) *mk_c = '_'; mk_c++; } } /* * get the result rows from the engine * * We cannot get the number of result lines, so we must * read them in a loop and save them into an temporary list. * Later, we can transfer this List into an MATLAB array of structs. * This way, we must allocate enough memory for two result sets, * but we save time by allocating the MATLAB Array at once. */ for(;;) { /* * Advance to teh next row */ int step_res = sqlite3_step(st); /* * no row left? break out of the loop */ if (step_res != SQLITE_ROW) break; /* * get new memory for the result */ Values* RecordValues = new Values(ncol); Value *v = RecordValues->m_Values; for (int j = 0; j < ncol; j++, v++) { int fieldtype = sqlite3_column_type(st,j); v->m_Type = fieldtype; switch (fieldtype) { case SQLITE_NULL: v->m_NumericValue = g_NaN; break; case SQLITE_INTEGER: v->m_NumericValue = (double) sqlite3_column_int(st, j); break; case SQLITE_FLOAT: v->m_NumericValue = (double) sqlite3_column_double(st, j); break; case SQLITE_TEXT: v->m_StringValue = strnewdup((const char*) sqlite3_column_text(st, j)); break; default: mxFree(command); mexErrMsgTxt(MSG_UNKNWNDBTYPE); } } /* * and add this row to the list of all result rows */ if (! lastrow) { allrows = lastrow = RecordValues; } else { lastrow->m_NextValues = RecordValues; lastrow = lastrow->m_NextValues; } /* * we have one more... */ rowcount ++; } /* * end the sql engine */ sqlite3_finalize(st); /* * got nothing? return an empty result to MATLAB */ if (rowcount == 0 || ! allrows) { if (!( plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL) )) { mxFree(command); mexErrMsgTxt(MSG_CANTCREATEOUTPUT); } } else { /* * Allocate an array of MATLAB structs to return as result */ int ndims[2]; ndims[0] = rowcount; ndims[1] = 1; if (( plhs[0] = mxCreateStructArray (2, ndims, ncol, (const char**)fieldnames)) == 0) { mxFree(command); mexErrMsgTxt(MSG_CANTCREATEOUTPUT); } /* * transfer the result rows from the temporary list into the result array */ lastrow = allrows; i = 0; while(lastrow) { Value* recordvalue = lastrow->m_Values; for (int j = 0; j < ncol; j++, recordvalue++) { if (recordvalue -> m_Type == SQLITE_TEXT) { mxArray* c = mxCreateString(recordvalue->m_StringValue); mxSetFieldByNumber(plhs[0], i, j, c); } else if (recordvalue -> m_Type == SQLITE_NULL && !NULLasNaN) { mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL); mxSetFieldByNumber(plhs[0], i, j, out_double); } else { mxArray* out_double = mxCreateDoubleScalar(recordvalue->m_NumericValue); mxSetFieldByNumber(plhs[0], i, j, out_double); } } allrows = lastrow; lastrow = lastrow->m_NextValues; delete allrows; i++; } } for(int i=0; i<ncol; i++) delete [] fieldnames[i]; delete [] fieldnames; } else { /* * no result, cleanup the sqlite engine */ int res = sqlite3_step(st); sqlite3_finalize(st); if (res != SQLITE_DONE) { mxFree(command); mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id])); } } } mxFree(command); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int i, j; mxArray *xm, *cell, *xm_cell; double *src; double *dest; double *dest_cell; int valid_vars; int steps; int this_var_errors; int warned_diags; int prepare_for_c = 0; int extra_solves; const char *status_names[] = {"optval", "gap", "steps", "converged"}; mwSize dims1x1of1[1] = {1}; mwSize dims[1]; const char *var_names[] = {"phi", "rho", "vd"}; const int num_var_names = 3; /* Avoid compiler warnings of unused variables by using a dummy assignment. */ warned_diags = j = 0; extra_solves = 0; set_defaults(); /* Check we got the right number of arguments. */ if (nrhs == 0) mexErrMsgTxt("Not enough arguments: You need to specify at least the parameters.\n"); if (nrhs > 1) { /* Assume that the second argument is the settings. */ if (mxGetField(prhs[1], 0, "eps") != NULL) settings.eps = *mxGetPr(mxGetField(prhs[1], 0, "eps")); if (mxGetField(prhs[1], 0, "max_iters") != NULL) settings.max_iters = *mxGetPr(mxGetField(prhs[1], 0, "max_iters")); if (mxGetField(prhs[1], 0, "refine_steps") != NULL) settings.refine_steps = *mxGetPr(mxGetField(prhs[1], 0, "refine_steps")); if (mxGetField(prhs[1], 0, "verbose") != NULL) settings.verbose = *mxGetPr(mxGetField(prhs[1], 0, "verbose")); if (mxGetField(prhs[1], 0, "better_start") != NULL) settings.better_start = *mxGetPr(mxGetField(prhs[1], 0, "better_start")); if (mxGetField(prhs[1], 0, "verbose_refinement") != NULL) settings.verbose_refinement = *mxGetPr(mxGetField(prhs[1], 0, "verbose_refinement")); if (mxGetField(prhs[1], 0, "debug") != NULL) settings.debug = *mxGetPr(mxGetField(prhs[1], 0, "debug")); if (mxGetField(prhs[1], 0, "kkt_reg") != NULL) settings.kkt_reg = *mxGetPr(mxGetField(prhs[1], 0, "kkt_reg")); if (mxGetField(prhs[1], 0, "s_init") != NULL) settings.s_init = *mxGetPr(mxGetField(prhs[1], 0, "s_init")); if (mxGetField(prhs[1], 0, "z_init") != NULL) settings.z_init = *mxGetPr(mxGetField(prhs[1], 0, "z_init")); if (mxGetField(prhs[1], 0, "resid_tol") != NULL) settings.resid_tol = *mxGetPr(mxGetField(prhs[1], 0, "resid_tol")); if (mxGetField(prhs[1], 0, "extra_solves") != NULL) extra_solves = *mxGetPr(mxGetField(prhs[1], 0, "extra_solves")); else extra_solves = 0; if (mxGetField(prhs[1], 0, "prepare_for_c") != NULL) prepare_for_c = *mxGetPr(mxGetField(prhs[1], 0, "prepare_for_c")); } valid_vars = 0; this_var_errors = 0; xm = mxGetField(prhs[0], 0, "A"); if (xm == NULL) { printf("could not find params.A.\n"); } else { if (!((mxGetM(xm) == 6) && (mxGetN(xm) == 34))) { printf("A must be size (6,34), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter A must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter A must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter A must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.A; src = mxGetPr(xm); for (i = 0; i < 204; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "C"); if (xm == NULL) { printf("could not find params.C.\n"); } else { if (!((mxGetM(xm) == 6) && (mxGetN(xm) == 6))) { printf("C must be size (6,6), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter C must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter C must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter C must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.C; src = mxGetPr(xm); warned_diags = 0; for (i = 0; i < 6; i++) { for (j = 0; j < 6; j++) { if (i == j) { *dest++ = *src; } else if (!warned_diags && (*src != 0)) { printf("\n!!! Warning: ignoring off-diagonal elements in C !!!\n\n"); warned_diags = 1; } src++; } } valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "Js"); if (xm == NULL) { printf("could not find params.Js.\n"); } else { if (!((mxGetM(xm) == 34) && (mxGetN(xm) == 34))) { printf("Js must be size (34,34), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter Js must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter Js must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter Js must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.Js; src = mxGetPr(xm); for (i = 0; i < 1156; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "Lambda"); if (xm == NULL) { printf("could not find params.Lambda.\n"); } else { if (!((mxGetM(xm) == 34) && (mxGetN(xm) == 34))) { printf("Lambda must be size (34,34), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter Lambda must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter Lambda must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter Lambda must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.Lambda; src = mxGetPr(xm); warned_diags = 0; for (i = 0; i < 34; i++) { for (j = 0; j < 34; j++) { if (i == j) { *dest++ = *src; } else if (!warned_diags && (*src != 0)) { printf("\n!!! Warning: ignoring off-diagonal elements in Lambda !!!\n\n"); warned_diags = 1; } src++; } } valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "Qphi"); if (xm == NULL) { printf("could not find params.Qphi.\n"); } else { if (!((mxGetM(xm) == 6) && (mxGetN(xm) == 10))) { printf("Qphi must be size (6,10), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter Qphi must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter Qphi must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter Qphi must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.Qphi; src = mxGetPr(xm); for (i = 0; i < 60; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "Qrho"); if (xm == NULL) { printf("could not find params.Qrho.\n"); } else { if (!((mxGetM(xm) == 6) && (mxGetN(xm) == 64))) { printf("Qrho must be size (6,64), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter Qrho must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter Qrho must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter Qrho must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.Qrho; src = mxGetPr(xm); for (i = 0; i < 384; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "WPhi"); if (xm == NULL) { printf("could not find params.WPhi.\n"); } else { if (!((mxGetM(xm) == 10) && (mxGetN(xm) == 10))) { printf("WPhi must be size (10,10), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter WPhi must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter WPhi must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter WPhi must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.WPhi; src = mxGetPr(xm); warned_diags = 0; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { if (i == j) { *dest++ = *src; } else if (!warned_diags && (*src != 0)) { printf("\n!!! Warning: ignoring off-diagonal elements in WPhi !!!\n\n"); warned_diags = 1; } src++; } } valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "WRho"); if (xm == NULL) { printf("could not find params.WRho.\n"); } else { if (!((mxGetM(xm) == 64) && (mxGetN(xm) == 64))) { printf("WRho must be size (64,64), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter WRho must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter WRho must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter WRho must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.WRho; src = mxGetPr(xm); warned_diags = 0; for (i = 0; i < 64; i++) { for (j = 0; j < 64; j++) { if (i == j) { *dest++ = *src; } else if (!warned_diags && (*src != 0)) { printf("\n!!! Warning: ignoring off-diagonal elements in WRho !!!\n\n"); warned_diags = 1; } src++; } } valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "WRhoSmoother"); if (xm == NULL) { printf("could not find params.WRhoSmoother.\n"); } else { if (!((mxGetM(xm) == 64) && (mxGetN(xm) == 64))) { printf("WRhoSmoother must be size (64,64), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter WRhoSmoother must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter WRhoSmoother must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter WRhoSmoother must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.WRhoSmoother; src = mxGetPr(xm); warned_diags = 0; for (i = 0; i < 64; i++) { for (j = 0; j < 64; j++) { if (i == j) { *dest++ = *src; } else if (!warned_diags && (*src != 0)) { printf("\n!!! Warning: ignoring off-diagonal elements in WRhoSmoother !!!\n\n"); warned_diags = 1; } src++; } } valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "Ws"); if (xm == NULL) { printf("could not find params.Ws.\n"); } else { if (!((mxGetM(xm) == 34) && (mxGetN(xm) == 34))) { printf("Ws must be size (34,34), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter Ws must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter Ws must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter Ws must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.Ws; src = mxGetPr(xm); warned_diags = 0; for (i = 0; i < 34; i++) { for (j = 0; j < 34; j++) { if (i == j) { *dest++ = *src; } else if (!warned_diags && (*src != 0)) { printf("\n!!! Warning: ignoring off-diagonal elements in Ws !!!\n\n"); warned_diags = 1; } src++; } } valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "b"); if (xm == NULL) { printf("could not find params.b.\n"); } else { if (!((mxGetM(xm) == 6) && (mxGetN(xm) == 1))) { printf("b must be size (6,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter b must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter b must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter b must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.b; src = mxGetPr(xm); for (i = 0; i < 6; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "c"); if (xm == NULL) { printf("could not find params.c.\n"); } else { if (!((mxGetM(xm) == 6) && (mxGetN(xm) == 1))) { printf("c must be size (6,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter c must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter c must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter c must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.c; src = mxGetPr(xm); for (i = 0; i < 6; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "phiMax"); if (xm == NULL) { printf("could not find params.phiMax.\n"); } else { if (!((mxGetM(xm) == 10) && (mxGetN(xm) == 1))) { printf("phiMax must be size (10,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter phiMax must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter phiMax must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter phiMax must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.phiMax; src = mxGetPr(xm); for (i = 0; i < 10; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "phiMin"); if (xm == NULL) { printf("could not find params.phiMin.\n"); } else { if (!((mxGetM(xm) == 10) && (mxGetN(xm) == 1))) { printf("phiMin must be size (10,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter phiMin must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter phiMin must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter phiMin must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.phiMin; src = mxGetPr(xm); for (i = 0; i < 10; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "ps"); if (xm == NULL) { printf("could not find params.ps.\n"); } else { if (!((mxGetM(xm) == 34) && (mxGetN(xm) == 1))) { printf("ps must be size (34,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter ps must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter ps must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter ps must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.ps; src = mxGetPr(xm); for (i = 0; i < 34; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "rhoMin"); if (xm == NULL) { printf("could not find params.rhoMin.\n"); } else { if (!((mxGetM(xm) == 64) && (mxGetN(xm) == 1))) { printf("rhoMin must be size (64,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter rhoMin must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter rhoMin must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter rhoMin must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.rhoMin; src = mxGetPr(xm); for (i = 0; i < 64; i++) *dest++ = *src++; valid_vars++; } } this_var_errors = 0; xm = mxGetField(prhs[0], 0, "rhoPrevious"); if (xm == NULL) { printf("could not find params.rhoPrevious.\n"); } else { if (!((mxGetM(xm) == 64) && (mxGetN(xm) == 1))) { printf("rhoPrevious must be size (64,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter rhoPrevious must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter rhoPrevious must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter rhoPrevious must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.rhoPrevious; src = mxGetPr(xm); for (i = 0; i < 64; i++) *dest++ = *src++; valid_vars++; } } if (valid_vars != 17) { printf("Error: %d parameters are invalid.\n", 17 - valid_vars); mexErrMsgTxt("invalid parameters found."); } if (prepare_for_c) { printf("settings.prepare_for_c == 1. thus, outputting for C.\n"); for (i = 0; i < 204; i++) printf(" params.A[%d] = %.6g;\n", i, params.A[i]); for (i = 0; i < 6; i++) printf(" params.b[%d] = %.6g;\n", i, params.b[i]); for (i = 0; i < 6; i++) printf(" params.C[%d] = %.6g;\n", i, params.C[i]); for (i = 0; i < 1156; i++) printf(" params.Js[%d] = %.6g;\n", i, params.Js[i]); for (i = 0; i < 34; i++) printf(" params.ps[%d] = %.6g;\n", i, params.ps[i]); for (i = 0; i < 34; i++) printf(" params.Ws[%d] = %.6g;\n", i, params.Ws[i]); for (i = 0; i < 64; i++) printf(" params.WRho[%d] = %.6g;\n", i, params.WRho[i]); for (i = 0; i < 10; i++) printf(" params.WPhi[%d] = %.6g;\n", i, params.WPhi[i]); for (i = 0; i < 34; i++) printf(" params.Lambda[%d] = %.6g;\n", i, params.Lambda[i]); for (i = 0; i < 64; i++) printf(" params.rhoPrevious[%d] = %.6g;\n", i, params.rhoPrevious[i]); for (i = 0; i < 64; i++) printf(" params.WRhoSmoother[%d] = %.6g;\n", i, params.WRhoSmoother[i]); for (i = 0; i < 384; i++) printf(" params.Qrho[%d] = %.6g;\n", i, params.Qrho[i]); for (i = 0; i < 60; i++) printf(" params.Qphi[%d] = %.6g;\n", i, params.Qphi[i]); for (i = 0; i < 6; i++) printf(" params.c[%d] = %.6g;\n", i, params.c[i]); for (i = 0; i < 64; i++) printf(" params.rhoMin[%d] = %.6g;\n", i, params.rhoMin[i]); for (i = 0; i < 10; i++) printf(" params.phiMin[%d] = %.6g;\n", i, params.phiMin[i]); for (i = 0; i < 10; i++) printf(" params.phiMax[%d] = %.6g;\n", i, params.phiMax[i]); } /* Perform the actual solve in here. */ steps = solve(); /* For profiling purposes, allow extra silent solves if desired. */ settings.verbose = 0; for (i = 0; i < extra_solves; i++) solve(); /* Update the status variables. */ plhs[1] = mxCreateStructArray(1, dims1x1of1, 4, status_names); xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[1], 0, "optval", xm); *mxGetPr(xm) = work.optval; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[1], 0, "gap", xm); *mxGetPr(xm) = work.gap; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[1], 0, "steps", xm); *mxGetPr(xm) = steps; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[1], 0, "converged", xm); *mxGetPr(xm) = work.converged; /* Extract variable values. */ plhs[0] = mxCreateStructArray(1, dims1x1of1, num_var_names, var_names); xm = mxCreateDoubleMatrix(10, 1, mxREAL); mxSetField(plhs[0], 0, "phi", xm); dest = mxGetPr(xm); src = vars.phi; for (i = 0; i < 10; i++) { *dest++ = *src++; } xm = mxCreateDoubleMatrix(64, 1, mxREAL); mxSetField(plhs[0], 0, "rho", xm); dest = mxGetPr(xm); src = vars.rho; for (i = 0; i < 64; i++) { *dest++ = *src++; } xm = mxCreateDoubleMatrix(34, 1, mxREAL); mxSetField(plhs[0], 0, "vd", xm); dest = mxGetPr(xm); src = vars.vd; for (i = 0; i < 34; i++) { *dest++ = *src++; } }