void mexProblem::ObtainElementFromMxArray(Element *X, const mxArray *Xmx) { // copy the main data from mxArray to X double *Xmxptr = mxGetPr(GetFieldbyName(Xmx, 0, "main")); integer lengthX = X->Getlength(); integer inc = 1; double *Xptr = X->ObtainWriteEntireData(); dcopy_(&lengthX, Xmxptr, &inc, Xptr, &inc); // copy temp data from mxArray to X integer nfields = mxGetNumberOfFields(Xmx); const char **fnames; mxArray *tmp; fnames = static_cast<const char **> (mxCalloc(nfields, sizeof(*fnames))); for (integer i = 0; i < nfields; i++) { fnames[i] = mxGetFieldNameByNumber(Xmx, i); if (strcmp(fnames[i], "main") != 0) { tmp = GetFieldbyName(Xmx, 0, fnames[i]); double *tmpptr = mxGetPr(tmp); integer length = mxGetM(tmp); SharedSpace *Sharedtmp = new SharedSpace(1, length); double *Sharedtmpptr = Sharedtmp->ObtainWriteEntireData(); dcopy_(&length, tmpptr, &inc, Sharedtmpptr, &inc); X->AddToTempData(fnames[i], Sharedtmp); } } };
const char *matlab_matrix_to_model(struct model *model_, const mxArray *matlab_struct) { int i, num_of_fields; int nr_w; double *ptr; int id = 0; int n, w_size; mxArray **rhs; num_of_fields = mxGetNumberOfFields(matlab_struct); rhs = (mxArray **) mxMalloc(sizeof(mxArray *)*num_of_fields); for(i=0;i<num_of_fields;i++) rhs[i] = mxGetFieldByNumber(matlab_struct, 0, i); model_->nr_class=0; nr_w=0; model_->nr_feature=0; model_->w=NULL; model_->label=NULL; // Parameters ptr = mxGetPr(rhs[id]); model_->param.solver_type = (int)ptr[0]; id++; // nr_class ptr = mxGetPr(rhs[id]); model_->nr_class = (int)ptr[0]; id++; if(model_->nr_class==2 && model_->param.solver_type != MCSVM_CS) nr_w=1; else nr_w=model_->nr_class; // nr_feature ptr = mxGetPr(rhs[id]); model_->nr_feature = (int)ptr[0]; id++; // bias ptr = mxGetPr(rhs[id]); model_->bias = (int)ptr[0]; id++; if(model_->bias>=0) n=model_->nr_feature+1; else n=model_->nr_feature; w_size = n; // Label if(mxIsEmpty(rhs[id]) == 0) { model_->label = Malloc(int, model_->nr_class); ptr = mxGetPr(rhs[id]); for(i=0;i<model_->nr_class;i++) model_->label[i] = (int)ptr[i]; }
ostrm& json( ostrm& S, const mxArray *M ) { // convert Matlab mxArray to JSON string siz i, j, m, n=mxGetNumberOfElements(M); void *A=mxGetData(M); ostrm *nms; switch( mxGetClassID(M) ) { case mxDOUBLE_CLASS: return json(S,(double*) A,n); case mxSINGLE_CLASS: return json(S,(float*) A,n); case mxINT64_CLASS: return json(S,(int64_t*) A,n); case mxUINT64_CLASS: return json(S,(uint64_t*) A,n); case mxINT32_CLASS: return json(S,(int32_t*) A,n); case mxUINT32_CLASS: return json(S,(uint32_t*) A,n); case mxINT16_CLASS: return json(S,(int16_t*) A,n); case mxUINT16_CLASS: return json(S,(uint16_t*) A,n); case mxINT8_CLASS: return json<int8_t,int32_t>(S,(int8_t*) A,n); case mxUINT8_CLASS: return json<uint8_t,uint32_t>(S,(uint8_t*) A,n); case mxLOGICAL_CLASS: return json<uint8_t,uint32_t>(S,(uint8_t*) A,n); case mxCHAR_CLASS: return json(S,mxArrayToString(M)); case mxCELL_CLASS: S << "["; for(i=0; i<n-1; i++) json(S,mxGetCell(M,i)) << ","; if(n>0) json(S,mxGetCell(M,n-1)); S << "]"; return S; case mxSTRUCT_CLASS: if(n==0) { S<<"{}"; return S; } m=mxGetNumberOfFields(M); if(m==0) { S<<"["; for(i=0; i<n; i++) S<<"{},"; S<<"]"; return S; } if(n>1) S<<"["; nms=new ostrm[m]; for(j=0; j<m; j++) json(nms[j],mxGetFieldNameByNumber(M,j)); for(i=0; i<n; i++) for(j=0; j<m; j++) { if(j==0) S << "{"; S << nms[j].str() << ":"; json(S,mxGetFieldByNumber(M,i,j)) << ((j<m-1) ? "," : "}"); if(j==m-1 && i<n-1) S<<","; } if(n>1) S<<"]"; delete [] nms; return S; default: mexErrMsgTxt( "Unknown type." ); return S; } }
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; }
int bind_params(sqlite3_stmt* stmt, const mxArray *params, int column) { TYPECHECK(params, mxSTRUCT_CLASS); int i, n = mxGetNumberOfFields(params); for (i = 0; i < n; i++) { mxArray *array = mxGetFieldByNumber(params, column, i); mxClassID cls = mxGetClassID(array); int res; switch (cls) { case mxFUNCTION_CLASS: break; case mxCHAR_CLASS: res = bind_string(stmt, i + 1, array); break; case mxSINGLE_CLASS: case mxDOUBLE_CLASS: res = bind_double(stmt, i + 1, array); break; default: /* anything else is an integer */ res = bind_int64(stmt, i + 1, array); } if (res != SQLITE_OK) { return res; } } return SQLITE_OK; }
/* * sample file that shows how to transform an array of structs * containing (id, handle) pairs to a callback list and return the * pointer to the data. the callback list can thus be passed to the * second file in this example (exec_callbacks.cpp). * * The passed matlab functions must not have any argument as this example here * doesn't take care of those arguments. */ void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs != 1) mexErrMsgTxt("Function requires exactly one argument.\n"); if (nlhs != 1) mexErrMsgTxt("Function returns exactly one value.\n"); if (!mxIsStruct(prhs[0])) mexErrMsgTxt("Function requires a structure array as argument\n"); int nfields = mxGetNumberOfFields(prhs[0]); mwSize nstructs = mxGetNumberOfElements(prhs[0]); std::vector<callback*> *cb_list = new std::vector<callback*>(); // parse each struct for (mwIndex i = 0; i < nstructs; i++) { bool id_found = false; bool fn_found = false; callback *cb = new callback(); for (int j = 0; j < nfields; j++) { mxArray *field = mxGetFieldByNumber(prhs[0], i, j); if (!field) { mexWarnMsgTxt("Invalid structure found\n"); continue; } const char *fname = mxGetFieldNameByNumber(prhs[0], j); if (!strncmp(fname, "id", sizeof("id"))) { if (!mxIsNumeric(field) || mxGetNumberOfElements(field) != 1) { mexWarnMsgTxt("Invalid id (must be numeric scalar).\n"); continue; } id_found = true; cb->id = (int)mxGetScalar(field); } else if (!strncmp(fname, "handle", sizeof("handle"))) { if (!mxIsClass(field, "function_handle")) { mexWarnMsgTxt("Invalid handle (must be function_handle).\n"); continue; } fn_found = true; cb->fn = field; } } if (!id_found || !fn_found) delete cb; else cb_list->push_back(cb); } // return the list plhs[0] = create_mex_obj(cb_list); }
mxArray *mexProblem::GetFieldbyName(const mxArray *S, integer idxstruct, const char *name) { integer nfields = mxGetNumberOfFields(S); for (integer i = 0; i < nfields; i++) { if (strcmp(mxGetFieldNameByNumber(S, i), name) == 0) { return mxGetFieldByNumber(S, idxstruct, i); } } return nullptr; };
void setCameraProperty(const EdsCameraRef handle, const mxArray* mxstruct) { if (mxIsStruct(mxstruct)) { unsigned numProperties = mxGetNumberOfFields(mxstruct); for (unsigned iterProperty = 0; iterProperty < numProperties; ++iterProperty) { setCameraProperty(handle, stringToCameraProperty(mxGetFieldNameByNumber(mxstruct, iterProperty)), \ mxGetFieldByNumber(mxstruct, 0, iterProperty)); } } else if (!mxIsEmpty(mxstruct)) { mexErrMsgIdAndTxt(ERROR_ID, "For setting multiple attributes, a struct array must be provided."); } }
const char *mxGetFieldNameByNumber(const mxArray *array_ptr, int field_number) { if (!mxIsStruct(array_ptr)) { return NULL; } if (field_number < 0 || field_number >= mxGetNumberOfFields(array_ptr)) { return NULL; } types::String *names = ((types::Struct*)array_ptr)->getFieldNames(); wchar_t *name = names->get(field_number); return (const char *)wide_string_to_UTF8(name); }
value_struct* get_structure_malloc(const mxArray* prhsi, int *numb_fields) { if (!mxIsStruct(prhsi)) { mexErrMsgTxt("Ask the programmer of this soft to clear up this issue"); } *numb_fields = mxGetNumberOfFields(prhsi); value_struct* structure = malloc(*numb_fields*sizeof(value_struct)); int k=0; for (k=0;k<*numb_fields;k++) { structure[k].name=malloc(sizeof(char)*strlen(mxGetFieldNameByNumber(prhsi,k))); structure[k].name=mxGetFieldNameByNumber(prhsi,k); structure[k].value=(mxGetPr(mxGetField(prhsi,0,mxGetFieldNameByNumber(prhsi,k))))[0]; } return structure; }
void readParameter( double * parameter, const mxArray * parameter_ptr ) { mxArray * tmp; int nfields = mxGetNumberOfFields(parameter_ptr); for(int ifield = 0, ip = 0; ifield < nfields; ifield ++) { // get the haarfeature(jstruct).field(ifield) tmp = mxGetFieldByNumber(parameter_ptr, 0, ifield); //haarfeature[jstruct][ifield] = tmp; if(mxIsDouble(tmp) && mxGetM(tmp) == 1 && mxGetN(tmp) == 1){ parameter[ip++] = mxGetPr(tmp)[0]; } } }
void mexFunction (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { int nfields; mxArray *tmp; char *vname = "velocity"; const char *fnames[2]; fnames[0] = "v"; fnames[1] = "v2"; if (nrhs != 1 || ! mxIsStruct (prhs[0]) || mxGetNumberOfElements (prhs[0]) != 1) mexErrMsgTxt ("Expects struct with only one element"); nfields = mxGetNumberOfFields(prhs[0]); plhs[0] = mxCreateStructMatrix(1, 1, 2, fnames); mexPrintf("You have %d fields\n", nfields); tmp = mxGetField(prhs[0],0,vname); if (tmp==NULL ){ mexPrintf("%s is not a field in the struct\n",vname); mexErrMsgTxt("Missing velocity field"); } //if (mxIsChar(tmp)){ //mexPrintf("field1 is a string");} //else{ //mexPrintf("field1 is NOT a string");} //fout = mxDuplicateArray(prhs[0]); //fout = mxCreateCellMatrix(1, 1); //mxSetCell( fout, 0, mxGetCell (prhs[0], 0)); //plhs[0] = mxGetFieldByNumber (mxGetCell (prhs[0], 0),0,0); //plhs[0] = tmp; }
mxArray *mxGetFieldByNumber(const mxArray *ptr, int lindex, int field_number) { if (!mxIsStruct(ptr)) { return NULL; } if (lindex >= mxGetNumberOfElements(ptr) || lindex < 0) { return NULL; } if (field_number >= mxGetNumberOfFields(ptr) || field_number < 0) { return NULL; } Struct *pa = (Struct *)ptr; String *names = pa->getFieldNames(); SingleStruct *s = pa->get(lindex); return (mxArray *)s->get(names->get(field_number)); }
bool parse(const mxArray* opts_in) { if (!mxIsStruct(opts_in)) { mexErrMsgTxt("Options parameter must be a structure.\n"); return (false); } int num_fields = mxGetNumberOfFields(opts_in); for (int fn=0; fn<num_fields; fn++) { const char* opt_name = mxGetFieldNameByNumber(opts_in, fn); std::string opt_name_str = opt_name; mxArray *opt_val = mxGetFieldByNumber(opts_in, 0, fn); if (opt_name_str == "num_max_iter") { num_max_iter = static_cast<size_t>(mxGetScalar(opt_val)); } else if (opt_name_str == "rho") { rho = mxGetScalar(opt_val); } else if (opt_name_str == "eps_gnorm") { eps_gnorm = mxGetScalar(opt_val); } else if (opt_name_str == "solver") { std::string solver_name = GetMatlabString(opt_val); if (solver_name == "fistadescent") { solver = SOLVER_FISTADESCENT; } else if (solver_name == "lbfgs") { solver = SOLVER_LBFGS; } else { mexErrMsgTxt("No solver with this name.\n"); return false; } } else { mexErrMsgTxt("Name of the option is invalid.\n"); return (false); } } return true; }
/* Pass analyze_structure a pointer to a structure mxArray. Each element in a structure mxArray holds one or more fields; each field holds zero or one mxArray. analyze_structure accesses every field of every element and displays information about it. */ static void analyze_structure(const mxArray *structure_array_ptr) { mwSize total_num_of_elements; mwIndex index; int number_of_fields, field_index; const char *field_name; const mxArray *field_array_ptr; mexPrintf("\n"); total_num_of_elements = mxGetNumberOfElements(structure_array_ptr); number_of_fields = mxGetNumberOfFields(structure_array_ptr); /* Walk through each structure element. */ for (index=0; index<total_num_of_elements; index++) { /* For the given index, walk through each field. */ for (field_index=0; field_index<number_of_fields; field_index++) { mexPrintf("\n\t\t"); display_subscript(structure_array_ptr, index); field_name = mxGetFieldNameByNumber(structure_array_ptr, field_index); mexPrintf(".%s\n", field_name); field_array_ptr = mxGetFieldByNumber(structure_array_ptr, index, field_index); if (field_array_ptr == NULL) { mexPrintf("\tEmpty Field\n"); } else { /* Display a top banner. */ mexPrintf("------------------------------------------------\n"); get_characteristics(field_array_ptr); analyze_class(field_array_ptr); mexPrintf("\n"); } } mexPrintf("\n\n"); } }
static void set_object_data(const mxArray *data) { OBJECT *obj; mxArray *pId = mxGetField(data,0,"id"); char id[256]; if (pId==NULL) output_error("set_object_data(const mxArray *data={...}) did not find a required object id field"); else if (mxGetString(pId,id,sizeof(id))) output_error("set_object_data(const mxArray *data={...}) couldn't read the object id field"); else if ((obj=object_find_name(id))==NULL) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't find object id", id); else { int i; for (i=0; i<mxGetNumberOfFields(data); i++) { const char *name; const mxArray *pField = mxGetFieldByNumber(data,0,i); char value[4096]; if ((name=mxGetFieldNameByNumber(data,i))==NULL) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the name of field %d", id, i); else if (strcmp(name,"id")==0 || strcmp(name,"class")==0) { /* these may not be changed */ } else if (pField==NULL) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the object field '%s' for object '%s'", id, name); else if (mxIsChar(pField) && mxGetString(pField,value,sizeof(value))) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the string value '%s' from field '%s'", id, value, name); else if (mxIsDouble(pField) && sprintf(value,"%lg",*(double*)mxGetPr(pField))<1) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the double value '%lg' from field '%s'", id, *(double*)mxGetPr(pField), name); else if (mxIsComplex(pField) && sprintf(value,"%lg%+lgi",*(double*)mxGetPr(pField),*(double*)mxGetPi(pField))<1) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the complex value '%lg%+lgi' from field '%s'", id, *(double*)mxGetPr(pField), *(double*)mxGetPi(pField), name); else if (mxIsUint32(pField) && sprintf(value,"%lu",*(unsigned int*)mxGetPr(pField))<1) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the uint32 value '%lu' from field '%s'", id, *(unsigned int*)mxGetPr(pField), name); else if (strcmp(value,ERROR)==0) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't use error value '%s'", id, value); else if (strcmp(value,NONE)==0 && strcpy(value,"")==NULL) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't clear empty value '%s'", id, value); else if (!object_set_value_by_name(obj,name,value)) output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the value '%s' into property '%s'", id, value, name); } } }
/* Convert a Matlab structure (an mxArray) to a "bbs_t" structure. This function also checks for the validity of the matlab structure "val". */ void array_to_bbs(const mxArray *val, bbs_t *bbs) { if (!mxIsStruct(val)) mexErrMsgTxt("The spline structure is not a structure."); if (mxGetNumberOfElements(val) != 1) mexErrMsgTxt("The spline structure must not be an array of structures."); if (mxGetNumberOfFields(val) != 7) mexErrMsgTxt("The spline structure must contain 7 fields."); bbs->umin = get_bbs_field_double(val, "umin"); bbs->umax = get_bbs_field_double(val, "umax"); bbs->nptsu = get_bbs_field_int(val, "nptsu"); bbs->vmin = get_bbs_field_double(val, "vmin"); bbs->vmax = get_bbs_field_double(val, "vmax"); bbs->nptsv = get_bbs_field_int(val, "nptsv"); bbs->valdim = get_bbs_field_int(val, "valdim"); }
bool ConnectionHeader::fromMatlab(const mxArray *array) { data_.reset(); if (!mxIsStruct(array) && !mxGetNumberOfElements(array) == 1) return false; data_.reset(new ros::M_string); int numberOfFields = mxGetNumberOfFields(array); for(int i = 0; i < numberOfFields; i++) { std::string key = mxGetFieldNameByNumber(array, i); const mxArray *value = mxGetFieldByNumber(array, 0, i); if (Options::isString(value)) { data_->insert(ros::StringPair(key, Options::getString(value))); } else if (Options::isDoubleScalar(value)) { data_->insert(ros::StringPair(key, boost::lexical_cast<std::string>(Options::getDoubleScalar(value)))); } else if (Options::isIntegerScalar(value)) { data_->insert(ros::StringPair(key, boost::lexical_cast<std::string>(Options::getIntegerScalar(value)))); } else if (Options::isLogicalScalar(value)) { data_->insert(ros::StringPair(key, boost::lexical_cast<std::string>(Options::getLogicalScalar(value)))); } } return true; }
void object(mxArray *ma, int i, json_object **jo){ int j = 0; int n = mxGetNumberOfFields(ma); mxArray *tmpma; json_object *tmpobj; *jo = json_object_new_object(); for(; j < n; j++){ bool needDestroy = false; tmpma = mxGetFieldByNumber(ma, i, j); if (tmpma == NULL){ /* Object is NULL, create an empty matrix instead */ tmpma = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL); needDestroy = true; } parse(tmpma, &tmpobj); json_object_object_add(*jo, mxGetFieldNameByNumber(ma, j), tmpobj); if (needDestroy) mxDestroyArray(tmpma); } }
const char *matlab_matrix_to_model(struct svm_model *model, const mxArray *matlab_struct) { int i, j, n, num_of_fields; double *ptr; int id = 0; struct svm_node *x_space; mxArray **rhs; num_of_fields = mxGetNumberOfFields(matlab_struct); rhs = (mxArray **) mxMalloc(sizeof(mxArray *)*num_of_fields); for(i=0;i<num_of_fields;i++) rhs[i] = mxGetFieldByNumber(matlab_struct, 0, i); model->rho = NULL; model->probA = NULL; model->probB = NULL; model->label = NULL; model->nSV = NULL; model->free_sv = 1; // XXX ptr = mxGetPr(rhs[id]); model->param.svm_type = (int)ptr[0]; model->param.kernel_type = (int)ptr[1]; model->param.degree = (int)ptr[2]; model->param.gamma = ptr[3]; model->param.coef0 = ptr[4]; id++; ptr = mxGetPr(rhs[id]); model->nr_class = (int)ptr[0]; id++; ptr = mxGetPr(rhs[id]); model->l = (int)ptr[0]; id++; // rho n = model->nr_class * (model->nr_class-1)/2; model->rho = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->rho[i] = ptr[i]; id++; // label if(mxIsEmpty(rhs[id]) == 0) { model->label = (int*) malloc(model->nr_class*sizeof(int)); ptr = mxGetPr(rhs[id]); for(i=0;i<model->nr_class;i++) model->label[i] = (int)ptr[i]; } id++; // probA, probB if(mxIsEmpty(rhs[id]) == 0 && mxIsEmpty(rhs[id+1]) == 0) { model->probA = (double*) malloc(n*sizeof(double)); model->probB = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->probA[i] = ptr[i]; ptr = mxGetPr(rhs[id+1]); for(i=0;i<n;i++) model->probB[i] = ptr[i]; } id += 2; // nSV if(mxIsEmpty(rhs[id]) == 0) { model->nSV = (int*) malloc(model->nr_class*sizeof(int)); ptr = mxGetPr(rhs[id]); for(i=0;i<model->nr_class;i++) model->nSV[i] = (int)ptr[i]; } id++; // sv_coef ptr = mxGetPr(rhs[id]); model->sv_coef = (double**) malloc((model->nr_class-1)*sizeof(double)); for( i=0 ; i< model->nr_class -1 ; i++ ) model->sv_coef[i] = (double*) malloc((model->l)*sizeof(double)); for(i = 0; i < model->nr_class - 1; i++) for(j = 0; j < model->l; j++) model->sv_coef[i][j] = ptr[i*(model->l)+j]; id++; // SV { int sr, sc, elements; int num_samples; mwIndex *ir, *jc; mxArray *pprhs[1], *pplhs[1]; // transpose SV pprhs[0] = rhs[id]; if(mexCallMATLAB(1, pplhs, 1, pprhs, "transpose")) return "cannot transpose SV matrix"; rhs[id] = pplhs[0]; sr = mxGetN(rhs[id]); sc = mxGetM(rhs[id]); ptr = mxGetPr(rhs[id]); ir = mxGetIr(rhs[id]); jc = mxGetJc(rhs[id]); num_samples = mxGetNzmax(rhs[id]); elements = num_samples + sr; model->SV = (struct svm_node **) malloc(sr * sizeof(struct svm_node *)); x_space = (struct svm_node *)malloc(elements * sizeof(struct svm_node)); // SV is in column for(i=0;i<sr;i++) { int low = jc[i], high = jc[i+1]; int x_index = 0; model->SV[i] = &x_space[low+i]; for(j=low;j<high;j++) { model->SV[i][x_index].index = ir[j] + 1; model->SV[i][x_index].value = ptr[j]; x_index++; } model->SV[i][x_index].index = -1; } id++; } mxFree(rhs); return NULL; }
int mxToBytes(const mxArray *mx, char *byteArray, int byteArrayLength) { int ii; int nInfoBytes=0, nDataBytes=0, nFreeBytes=0; mxGramInfo info; // for complex types int jj; int nElements; mxArray *elementData, *elementName; char *elementByteArray; int elementGramLength; mxArray *callMatlabError; if (mx == NULL) return(0); info.gramBytes = byteArray; setInfoFieldsFromMx(&info, mx); info.dataBytes = byteArray + MX_GRAM_OFFSET_DATA; nFreeBytes = byteArrayLength - MX_GRAM_OFFSET_DATA; if (info.gramType==mxGramDouble) { nDataBytes = writeMxDoubleDataToBytes(mx, &info, nFreeBytes); } else if (info.gramType==mxGramChar) { nDataBytes = writeMxCharDataToBytes(mx, &info, nFreeBytes); } else if (info.gramType==mxGramLogical) { nDataBytes = writeMxLogicalDataToBytes(mx, &info, nFreeBytes); } else if (info.gramType==mxGramCell) { // recur to write data for each cell element nElements = info.dataM * info.dataN; elementByteArray = info.dataBytes; elementGramLength = 0; for (ii=0; ii<nElements; ii++) { elementData = mxGetCell(mx, ii); elementGramLength = mxToBytes((const mxArray*)elementData, elementByteArray, nFreeBytes); if (elementGramLength < 0) return(elementGramLength); nDataBytes += elementGramLength; elementByteArray += elementGramLength; nFreeBytes -= elementGramLength; } } else if (info.gramType==mxGramStruct) { // struct arrays resized to 1xn, with m fields nElements = mxGetNumberOfFields(mx); info.dataM = nElements; info.dataN = mxGetM(mx) * mxGetN(mx); // recur to write data for each field name elementByteArray = info.dataBytes; elementGramLength = 0; for (ii=0; ii<nElements; ii++) { elementName = mxCreateString(mxGetFieldNameByNumber(mx, ii)); elementGramLength = mxToBytes(elementName, elementByteArray, nFreeBytes); mxDestroyArray(elementName); if (elementGramLength < 0) return(elementGramLength); nDataBytes += elementGramLength; elementByteArray += elementGramLength; nFreeBytes -= elementGramLength; } // recur to write data for each field datum for (ii=0; ii<nElements; ii++) { for (jj=0; jj<info.dataN; jj++) { elementData = mxGetFieldByNumber(mx, jj, ii); elementGramLength = mxToBytes((const mxArray*)elementData, elementByteArray, nFreeBytes); if (elementGramLength < 0) return(elementGramLength); nDataBytes += elementGramLength; elementByteArray += elementGramLength; nFreeBytes -= elementGramLength; } } } else if (info.gramType==mxGramFunctionHandle) { // recur to write stringified version of function callMatlabError = mexCallMATLABWithTrap(1, &elementData, 1, (mxArray**)&mx, MX_GRAM_FUNCTION_TO_STRING); if (callMatlabError == NULL && elementData != NULL) { nDataBytes = mxToBytes((const mxArray*)elementData, info.dataBytes, nFreeBytes); if (nDataBytes < 0) return(nDataBytes); } else return(-1); } else { return(mxGramUnsupported); } //mexPrintf("nDataBytes = %d\n", nDataBytes); if (nDataBytes < 0) return(nDataBytes); info.gramLength = MX_GRAM_OFFSET_DATA + nDataBytes; nInfoBytes = writeInfoFieldsToBytes(&info, byteArray, byteArrayLength); //mexPrintf("nInfoBytes = %d\n", nInfoBytes); //printMxGramInfo(&info); //printBytes(info.gramBytes, info.gramLength); return(info.gramLength); }
struct svm_model *matlab_matrix_to_model(const mxArray *matlab_struct, const char **msg) { int i, j, n, num_of_fields; double *ptr; int id = 0; struct svm_node *x_space; struct svm_model *model; mxArray **rhs; num_of_fields = mxGetNumberOfFields(matlab_struct); if(num_of_fields != NUM_OF_RETURN_FIELD) { *msg = "number of return field is not correct"; return NULL; } rhs = (mxArray **) mxMalloc(sizeof(mxArray *)*num_of_fields); for(i=0;i<num_of_fields;i++) rhs[i] = mxGetFieldByNumber(matlab_struct, 0, i); model = Malloc(struct svm_model, 1); model->rho = NULL; model->probA = NULL; model->probB = NULL; model->label = NULL; model->nSV = NULL; model->free_sv = 1; /* XXX */ ptr = mxGetPr(rhs[id]); model->param.svm_type = (int)ptr[0]; model->param.kernel_type = (int)ptr[1]; model->param.degree = (int)ptr[2]; model->param.gamma = ptr[3]; model->param.coef0 = ptr[4]; id++; ptr = mxGetPr(rhs[id]); model->nr_class = (int)ptr[0]; id++; ptr = mxGetPr(rhs[id]); model->l = (int)ptr[0]; id++; /* rho */ n = model->nr_class * (model->nr_class-1)/2; model->rho = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->rho[i] = ptr[i]; id++; /* label */ if(mxIsEmpty(rhs[id]) == 0) { model->label = (int*) malloc(model->nr_class*sizeof(int)); ptr = mxGetPr(rhs[id]); for(i=0;i<model->nr_class;i++) model->label[i] = (int)ptr[i]; } id++; /* probA */ if(mxIsEmpty(rhs[id]) == 0) { model->probA = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->probA[i] = ptr[i]; } id++; /* probB */ if(mxIsEmpty(rhs[id]) == 0) { model->probB = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->probB[i] = ptr[i]; } id++; /* nSV */ if(mxIsEmpty(rhs[id]) == 0) { model->nSV = (int*) malloc(model->nr_class*sizeof(int)); ptr = mxGetPr(rhs[id]); for(i=0;i<model->nr_class;i++) model->nSV[i] = (int)ptr[i]; } id++; /* sv_coef */ ptr = mxGetPr(rhs[id]); model->sv_coef = (double**) malloc((model->nr_class-1)*sizeof(double)); for( i=0 ; i< model->nr_class -1 ; i++ ) model->sv_coef[i] = (double*) malloc((model->l)*sizeof(double)); for(i = 0; i < model->nr_class - 1; i++) for(j = 0; j < model->l; j++) model->sv_coef[i][j] = ptr[i*(model->l)+j]; id++; /* SV */ { int sr, sc, elements; int num_samples; mwIndex *ir, *jc; mxArray *pprhs[1], *pplhs[1]; /* transpose SV */ pprhs[0] = rhs[id]; if(mexCallMATLAB(1, pplhs, 1, pprhs, "transpose")) { svm_destroy_model(model); *msg = "cannot transpose SV matrix"; return NULL; } rhs[id] = pplhs[0]; sr = (int)mxGetN(rhs[id]); sc = (int)mxGetM(rhs[id]); ptr = mxGetPr(rhs[id]); ir = mxGetIr(rhs[id]); jc = mxGetJc(rhs[id]); num_samples = (int)mxGetNzmax(rhs[id]); elements = num_samples + sr; model->SV = (struct svm_node **) malloc(sr * sizeof(struct svm_node *)); x_space = (struct svm_node *)malloc(elements * sizeof(struct svm_node)); /* SV is in column */ for(i=0;i<sr;i++) { int low = (int)jc[i], high = (int)jc[i+1]; int x_index = 0; model->SV[i] = &x_space[low+i]; for(j=low;j<high;j++) { model->SV[i][x_index].index = (int)ir[j] + 1; model->SV[i][x_index].value = ptr[j]; x_index++; } model->SV[i][x_index].index = -1; } id++; } mxFree(rhs); return model; }
void mexFunction ( /* === Parameters ======================================================= */ int nlhs, /* number of left-hand sides */ mxArray *plhs [], /* left-hand side matrices */ int nrhs, /* number of right--hand sides */ const mxArray *prhs [] /* right-hand side matrices */ ) { Dmat A; DILUPACKparam param; const char **fnames; /* pointers to field names */ const mwSize *dims; mxClassID *classIDflags; mwSize buflen, mrows, ncols, ndim; mxArray *tmp, *fout, *A_input, *options_input, *options_output; char *pdata, *input_buf, *output_buf; int ifield, status, nfields; size_t sizebuf; double dbuf; if (nrhs != 2) mexErrMsgTxt("Two input arguments required."); else if (nlhs > 1) mexErrMsgTxt("Too many output arguments."); else if (!mxIsStruct(prhs[1])) mexErrMsgTxt("Second input must be a structure."); else if (!mxIsNumeric(prhs[0])) mexErrMsgTxt("First input must be a matrix."); /* The first input must be a square matrix.*/ A_input=(mxArray *)prhs[0]; mrows = mxGetM(A_input); ncols = mxGetN(A_input); if (mrows!=ncols) { mexErrMsgTxt("First input must be a square matrix."); } A.nc=A.nr=mrows; A.ia=A.ja=NULL; A.a=NULL; DSYMAMGinit(&A,¶m); /* Get second input arguments */ options_input=(mxArray *)prhs[1]; nfields = mxGetNumberOfFields(options_input); /* Allocate memory for storing pointers */ fnames = mxCalloc((size_t)nfields, (size_t)sizeof(*fnames)); /* Allocate memory for storing classIDflags */ classIDflags = (mxClassID *) mxCalloc((size_t)nfields, (size_t)sizeof(mxClassID)); /* Get field name pointers */ for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(options_input,ifield); } /* Create a 1x1 struct matrix for output */ nlhs=1; plhs[0] = mxCreateStructMatrix((mwSize)1, (mwSize)1, nfields, fnames); options_output=plhs[0]; /* copy data */ for (ifield = 0; ifield < nfields; ifield++) { tmp = mxGetFieldByNumber(options_input,(mwIndex)0,ifield); classIDflags[ifield] = mxGetClassID(tmp); ndim = mxGetNumberOfDimensions(tmp); dims = mxGetDimensions(tmp); /* Create string/numeric array */ if (classIDflags[ifield] == mxCHAR_CLASS) { /* Get the length of the input string. */ buflen = (mxGetM(tmp) * mxGetN(tmp)) + 1; if (!strcmp("amg",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.amg)+1, (size_t)sizeof(char)); strcpy(output_buf,param.amg); fout = mxCreateString(output_buf); } else if (!strcmp("presmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.presmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param.presmoother); fout = mxCreateString(output_buf); } else if (!strcmp("postsmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.postsmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param.postsmoother); fout = mxCreateString(output_buf); } else if (!strcmp("typecoarse",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.typecoarse)+1, (size_t)sizeof(char)); strcpy(output_buf,param.typecoarse); fout = mxCreateString(output_buf); } else if (!strcmp("typetv",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.typetv)+1, (size_t)sizeof(char)); strcpy(output_buf,param.typetv); fout = mxCreateString(output_buf); } else if (!strcmp("FCpart",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.FCpart)+1, (size_t)sizeof(char)); strcpy(output_buf,param.FCpart); fout = mxCreateString(output_buf); } else if (!strcmp("solver",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.solver)+1, (size_t)sizeof(char)); strcpy(output_buf, param.solver); fout = mxCreateString(output_buf); } else if (!strcmp("ordering",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param.ordering)+1, (size_t)sizeof(char)); strcpy(output_buf, param.ordering); fout = mxCreateString(output_buf); } else { /* Allocate memory for input and output strings. */ input_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); output_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); /* Copy the string data from tmp into a C string input_buf. */ status = mxGetString(tmp, input_buf, buflen); sizebuf = buflen*sizeof(char); memcpy(output_buf, input_buf, (size_t)sizebuf); fout = mxCreateString(output_buf); } } else { fout = mxCreateNumericArray((mwSize)ndim, dims, classIDflags[ifield], mxREAL); pdata = mxGetData(fout); sizebuf = mxGetElementSize(tmp); if (!strcmp("elbow",fnames[ifield])) { dbuf=param.elbow; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("lfilS",fnames[ifield])) { dbuf=param.lfilS; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("lfil",fnames[ifield])) { dbuf=param.lfil; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("maxit",fnames[ifield])) { dbuf=param.maxit; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("droptolS",fnames[ifield])) { dbuf=param.droptolS; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("droptolc",fnames[ifield])) { dbuf=param.droptolc; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("droptol",fnames[ifield])) { dbuf=param.droptol; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("condest",fnames[ifield])) { dbuf=param.condest; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("restol",fnames[ifield])) { dbuf=param.restol; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("npresmoothing",fnames[ifield])) { dbuf=param.npresmoothing; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("npostmoothing",fnames[ifield])) { dbuf=param.npostsmoothing; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("ncoarse",fnames[ifield])) { dbuf=param.ncoarse; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("matching",fnames[ifield])) { dbuf=param.matching; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("nrestart",fnames[ifield])) { dbuf=param.nrestart; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("damping",fnames[ifield])) { dbuf=param.damping; memcpy(pdata, &dbuf, (size_t)sizebuf); } else if (!strcmp("mixedprecision",fnames[ifield])) { dbuf=param.mixedprecision; memcpy(pdata, &dbuf, (size_t)sizebuf); } else { memcpy(pdata, mxGetData(tmp), (size_t)sizebuf); } } /* Set each field in output structure */ mxSetFieldByNumber(options_output, (mwIndex)0, ifield, fout); } mxFree(fnames); return; }
/* * s e t u p O p t i o n s */ returnValue setupOptions( Options* options, const mxArray* optionsPtr, int_t& nWSRin, real_t& maxCpuTime ) { double* optionValue; int_t optionValueInt; /* Check for correct number of option entries; * may occur, e.g., if user types options.<misspelledName> = <someValue>; */ if ( mxGetNumberOfFields(optionsPtr) != 31 ) mexWarnMsgTxt( "Options might be set incorrectly as struct has wrong number of entries!\n Type 'help qpOASES_options' for further information." ); if ( hasOptionsValue( optionsPtr,"maxIter",&optionValue ) == BT_TRUE ) if ( *optionValue >= 0.0 ) nWSRin = (int_t)*optionValue; if ( hasOptionsValue( optionsPtr,"maxCpuTime",&optionValue ) == BT_TRUE ) if ( *optionValue >= 0.0 ) maxCpuTime = *optionValue; if ( hasOptionsValue( optionsPtr,"printLevel",&optionValue ) == BT_TRUE ) { #ifdef __SUPPRESSANYOUTPUT__ options->printLevel = PL_NONE; #else optionValueInt = (int_t)*optionValue; options->printLevel = (REFER_NAMESPACE_QPOASES PrintLevel)optionValueInt; if ( options->printLevel < PL_DEBUG_ITER ) options->printLevel = PL_DEBUG_ITER; if ( options->printLevel > PL_HIGH ) options->printLevel = PL_HIGH; #endif } if ( hasOptionsValue( optionsPtr,"enableRamping",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; options->enableRamping = (REFER_NAMESPACE_QPOASES BooleanType)optionValueInt; } if ( hasOptionsValue( optionsPtr,"enableFarBounds",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; options->enableFarBounds = (REFER_NAMESPACE_QPOASES BooleanType)optionValueInt; } if ( hasOptionsValue( optionsPtr,"enableFlippingBounds",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; options->enableFlippingBounds = (REFER_NAMESPACE_QPOASES BooleanType)optionValueInt; } if ( hasOptionsValue( optionsPtr,"enableRegularisation",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; options->enableRegularisation = (REFER_NAMESPACE_QPOASES BooleanType)optionValueInt; } if ( hasOptionsValue( optionsPtr,"enableFullLITests",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; options->enableFullLITests = (REFER_NAMESPACE_QPOASES BooleanType)optionValueInt; } if ( hasOptionsValue( optionsPtr,"enableNZCTests",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; options->enableNZCTests = (REFER_NAMESPACE_QPOASES BooleanType)optionValueInt; } if ( hasOptionsValue( optionsPtr,"enableDriftCorrection",&optionValue ) == BT_TRUE ) options->enableDriftCorrection = (int_t)*optionValue; if ( hasOptionsValue( optionsPtr,"enableCholeskyRefactorisation",&optionValue ) == BT_TRUE ) options->enableCholeskyRefactorisation = (int_t)*optionValue; if ( hasOptionsValue( optionsPtr,"enableEqualities",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; options->enableEqualities = (REFER_NAMESPACE_QPOASES BooleanType)optionValueInt; } if ( hasOptionsValue( optionsPtr,"terminationTolerance",&optionValue ) == BT_TRUE ) options->terminationTolerance = *optionValue; if ( hasOptionsValue( optionsPtr,"boundTolerance",&optionValue ) == BT_TRUE ) options->boundTolerance = *optionValue; if ( hasOptionsValue( optionsPtr,"boundRelaxation",&optionValue ) == BT_TRUE ) options->boundRelaxation = *optionValue; if ( hasOptionsValue( optionsPtr,"epsNum",&optionValue ) == BT_TRUE ) options->epsNum = *optionValue; if ( hasOptionsValue( optionsPtr,"epsDen",&optionValue ) == BT_TRUE ) options->epsDen = *optionValue; if ( hasOptionsValue( optionsPtr,"maxPrimalJump",&optionValue ) == BT_TRUE ) options->maxPrimalJump = *optionValue; if ( hasOptionsValue( optionsPtr,"maxDualJump",&optionValue ) == BT_TRUE ) options->maxDualJump = *optionValue; if ( hasOptionsValue( optionsPtr,"initialRamping",&optionValue ) == BT_TRUE ) options->initialRamping = *optionValue; if ( hasOptionsValue( optionsPtr,"finalRamping",&optionValue ) == BT_TRUE ) options->finalRamping = *optionValue; if ( hasOptionsValue( optionsPtr,"initialFarBounds",&optionValue ) == BT_TRUE ) options->initialFarBounds = *optionValue; if ( hasOptionsValue( optionsPtr,"growFarBounds",&optionValue ) == BT_TRUE ) options->growFarBounds = *optionValue; if ( hasOptionsValue( optionsPtr,"initialStatusBounds",&optionValue ) == BT_TRUE ) { optionValueInt = (int_t)*optionValue; if ( optionValueInt < -1 ) optionValueInt = -1; if ( optionValueInt > 1 ) optionValueInt = 1; options->initialStatusBounds = (REFER_NAMESPACE_QPOASES SubjectToStatus)optionValueInt; } if ( hasOptionsValue( optionsPtr,"epsFlipping",&optionValue ) == BT_TRUE ) options->epsFlipping = *optionValue; if ( hasOptionsValue( optionsPtr,"numRegularisationSteps",&optionValue ) == BT_TRUE ) options->numRegularisationSteps = (int_t)*optionValue; if ( hasOptionsValue( optionsPtr,"epsRegularisation",&optionValue ) == BT_TRUE ) options->epsRegularisation = *optionValue; if ( hasOptionsValue( optionsPtr,"numRefinementSteps",&optionValue ) == BT_TRUE ) options->numRefinementSteps = (int_t)*optionValue; if ( hasOptionsValue( optionsPtr,"epsIterRef",&optionValue ) == BT_TRUE ) options->epsIterRef = *optionValue; if ( hasOptionsValue( optionsPtr,"epsLITests",&optionValue ) == BT_TRUE ) options->epsLITests = *optionValue; if ( hasOptionsValue( optionsPtr,"epsNZCTests",&optionValue ) == BT_TRUE ) options->epsNZCTests = *optionValue; return SUCCESSFUL_RETURN; }
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { // Input params are (in order) xIndices,yIndices,imgpatches,simMapParams (a structure), nChannels // IMPORTANT: DO NOT modify any thing in prhs please. COMindextype numRadiiIntervals,numThetaIntervals,numDescriptors; COMindextype interiorH,numSSDs,numAutoVarianceIndices; COMindextype *xIndices,*yIndices; COMindextype **binIndices; COMindextype* numBinIndices; COMindextype numBins; COMindextype nChannels; COMbasetype varNoise; int *coRelCircleOffsets; int nFields,nStructElements; COMindextype *autoVarianceIndices; mxArray *tmpArray,*cellArrayPtr; int numPatches,dimPatches; if (nrhs<5) usagerr("Atleast Five inputs are required.\n"); if (nlhs!=1) usagerr("One output is required.\n"); if (mxGetClassID(prhs[0])!=mxUINT32_CLASS) usagerr("xIndices must be of unsigned int.\n"); if (mxGetClassID(prhs[1])!=mxUINT32_CLASS) usagerr("yIndices must be of unsigned int.\n"); if (mxGetClassID(prhs[2])!=mxDOUBLE_CLASS) usagerr("imgpatches must be of type double.\n"); if (mxGetClassID(prhs[3])!=mxSTRUCT_CLASS) usagerr("simMapParams must be a structure.\n"); if (mxGetClassID(prhs[4])!=mxUINT32_CLASS) usagerr("nChannels must be a uint32.\n"); xIndices=(COMindextype*)mxGetData(prhs[0]); yIndices=(COMindextype*)mxGetData(prhs[1]); numPatches=mxGetN(prhs[2])/3; // 3 channel image dimPatches=mxGetM(prhs[2]); //mexPrintf("numPatches=%d,dimPatches=%d\n",numPatches,dimPatches);return; //numXIndices=mxGetN(prhs[0]);numYIndices=mxGetN(prhs[1]); //numDescriptors=numXIndices*numYIndices; numDescriptors=mxGetN(prhs[0]); if(mxGetN(prhs[1])!=numDescriptors) usagerr("number of x-coordinates != number of y-coordinates; Exiting\n"); nChannels=*(COMindextype*)mxGetData(prhs[4]); nFields=mxGetNumberOfFields(prhs[3]); nStructElements=mxGetNumberOfElements(prhs[3]); tmpArray=mxGetField(prhs[3],0,"interiorH"); if(mxGetClassID(tmpArray)!=mxUINT32_CLASS) usagerr("interior Height, should be uint32\n"); interiorH=(*(COMindextype*)mxGetData(tmpArray)); tmpArray=mxGetField(prhs[3],0,"numRadiiIntervals"); if(mxGetClassID(tmpArray)!=mxUINT32_CLASS) usagerr("numRadiiIntervals , should be uint32\n"); numRadiiIntervals=(*(COMindextype*)mxGetData(tmpArray)); tmpArray=mxGetField(prhs[3],0,"numThetaIntervals"); if(mxGetClassID(tmpArray)!=mxUINT32_CLASS) usagerr("numThetaIntervals, should be uint32\n"); numThetaIntervals=(*(COMindextype*)mxGetData(tmpArray)); tmpArray=mxGetField(prhs[3],0,"coRelCircleOffsets"); if(mxGetClassID(tmpArray)!=mxINT32_CLASS) usagerr("coRelCircleOffsets, should be int32\n"); coRelCircleOffsets=(int*)mxGetData(tmpArray); numSSDs=mxGetN(tmpArray); tmpArray=mxGetField(prhs[3],0,"autoVarianceIndices"); if(mxGetClassID(tmpArray)!=mxUINT32_CLASS) usagerr("autoVarianceIndices, should be uint32\n"); autoVarianceIndices=(COMindextype*)mxGetData(tmpArray); numAutoVarianceIndices=mxGetM(tmpArray); tmpArray=mxGetField(prhs[3],0,"varNoise"); if(mxGetClassID(tmpArray)!=mxDOUBLE_CLASS) usagerr("varNoise, should be double\n"); varNoise=*mxGetPr(tmpArray); cellArrayPtr=mxGetField(prhs[3],0,"binIndices"); if(mxGetClassID(cellArrayPtr)!=mxCELL_CLASS) usagerr("binIndices, should be cell class type\n"); numBins=mxGetNumberOfElements(cellArrayPtr); binIndices=(COMindextype**)mxMalloc(sizeof(COMindextype*)*numBins); numBinIndices=(COMindextype*)mxMalloc(sizeof(COMindextype)*numBins); //mexPrintf("numBins=%d\n",numBins); for(int i=0;i<numBins;i++){ tmpArray=mxGetCell(cellArrayPtr,i); if(mxGetClassID(tmpArray)!=mxUINT32_CLASS) usagerr("binIndices , should be uint32 type\n"); binIndices[i]=(COMindextype*)mxGetData(tmpArray); numBinIndices[i]=mxGetM(tmpArray); //mexPrintf("numBinIndices[%d]=%d\n",i,numBinIndices[i]); } if(nChannels==3){ COMmatrix imgPatches[3]; imgPatches[0]=(COMmatrix)mxGetData(prhs[2]); imgPatches[1]=numPatches*dimPatches+imgPatches[0]; imgPatches[2]=numPatches*dimPatches+imgPatches[1]; COMmatrix curPatch[3]; COMmatrix ssdS=(COMmatrix)mxMalloc(sizeof(COMbasetype)*numSSDs); COMindextype descSize=numThetaIntervals*numRadiiIntervals; plhs[0]=mxCreateDoubleMatrix(descSize,numDescriptors,mxREAL); COMmatrix outTraveller=(COMmatrix)mxGetData(plhs[0]); //mexPrintf("0=%f 1=%f 2=%f\n",(float)*imgPatches[0],(float)(*imgPatches[1]),(float)*imgPatches[2]); //mexPrintf("x= %d, y=%d \n",numXIndices,numYIndices); for(int x=0;x<numDescriptors;x++,xIndices++,yIndices++){ curPatch[0]=imgPatches[0]+((*xIndices)*interiorH+(*yIndices))*dimPatches; curPatch[1]=imgPatches[1]+((*xIndices)*interiorH+(*yIndices))*dimPatches; curPatch[2]=imgPatches[2]+((*xIndices)*interiorH+(*yIndices))*dimPatches; int* offsetTraveller=coRelCircleOffsets; COMmatrix ssdTraveller=ssdS; COMmatrix tmpPatch[3],tmpPatch2[3]; for(int i=0;i<numSSDs;i++,offsetTraveller++,ssdTraveller++){ *ssdTraveller=0; tmpPatch[0]=curPatch[0]+(*offsetTraveller)*dimPatches; tmpPatch[1]=curPatch[1]+(*offsetTraveller)*dimPatches; tmpPatch[2]=curPatch[2]+(*offsetTraveller)*dimPatches; tmpPatch2[0]=curPatch[0]; tmpPatch2[1]=curPatch[1]; tmpPatch2[2]=curPatch[2]; for(int j=0;j<dimPatches;j++){ COMbasetype diff; diff=*tmpPatch2[0]-*tmpPatch[0];tmpPatch[0]++;tmpPatch2[0]++; *ssdTraveller+=diff*diff; diff=*tmpPatch2[1]-*tmpPatch[1];tmpPatch[1]++;tmpPatch2[1]++; *ssdTraveller+=diff*diff; diff=*tmpPatch2[2]-*tmpPatch[2];tmpPatch[2]++;tmpPatch2[2]++; *ssdTraveller+=diff*diff; } } COMbasetype autoQ=0; for(int j=0;j<numAutoVarianceIndices;j++){ COMbasetype tmp=ssdS[autoVarianceIndices[j]]; autoQ=(tmp>autoQ)?tmp:autoQ; } COMbasetype divisor= (autoQ>varNoise)?autoQ:varNoise; ssdTraveller=ssdS; for(int k=0;k<numSSDs;k++,ssdTraveller++) *ssdTraveller=exp(-1*(*ssdTraveller)/divisor); for(int l=0;l<numBins;l++,outTraveller++){ COMbasetype max=0; COMindextype* curBinIndices=binIndices[l]; for(int j=0;j<numBinIndices[l];j++){ if(ssdS[curBinIndices[j]] > max) max=ssdS[curBinIndices[j]]; } *outTraveller=max; } } mxFree(ssdS);mxFree(binIndices);mxFree(numBinIndices); } else if(nChannels==1){ COMmatrix imgPatches; imgPatches=(COMmatrix)mxGetData(prhs[2]); COMmatrix curPatch; COMmatrix ssdS=(COMmatrix)mxMalloc(sizeof(COMbasetype)*numSSDs); COMindextype descSize=numThetaIntervals*numRadiiIntervals; plhs[0]=mxCreateDoubleMatrix(descSize,numDescriptors,mxREAL); COMmatrix outTraveller=(COMmatrix)mxGetData(plhs[0]); //mexPrintf("0=%f 1=%f 2=%f\n",(float)*imgPatches[0],(float)(*imgPatches[1]),(float)*imgPatches[2]); //mexPrintf("x= %d, y=%d \n",numXIndices,numYIndices); for(int x=0;x<numDescriptors;x++,xIndices++,yIndices++){ curPatch=imgPatches+((*xIndices)*interiorH+(*yIndices))*dimPatches; int* offsetTraveller=coRelCircleOffsets; COMmatrix ssdTraveller=ssdS; COMmatrix tmpPatch,tmpPatch2; for(int i=0;i<numSSDs;i++,offsetTraveller++,ssdTraveller++){ *ssdTraveller=0; tmpPatch=curPatch+(*offsetTraveller)*dimPatches; tmpPatch2=curPatch; for(int j=0;j<dimPatches;j++){ COMbasetype diff; diff=*tmpPatch2-*tmpPatch;tmpPatch++;tmpPatch2++; *ssdTraveller+=diff*diff; } } COMbasetype autoQ=0; for(int j=0;j<numAutoVarianceIndices;j++){ COMbasetype tmp=ssdS[autoVarianceIndices[j]]; autoQ=(tmp>autoQ)?tmp:autoQ; } COMbasetype divisor= (autoQ>varNoise)?autoQ:varNoise; ssdTraveller=ssdS; for(int k=0;k<numSSDs;k++,ssdTraveller++) *ssdTraveller=exp(-1*(*ssdTraveller)/divisor); for(int l=0;l<numBins;l++,outTraveller++){ COMbasetype max=0; COMindextype* curBinIndices=binIndices[l]; for(int j=0;j<numBinIndices[l];j++){ if(ssdS[curBinIndices[j]] > max) max=ssdS[curBinIndices[j]]; } *outTraveller=max; } } mxFree(ssdS);mxFree(binIndices);mxFree(numBinIndices); } else{ mexPrintf("nChannels=%d\n");usagerr("nChannels can only be 1 or 3\n");} // Free: }
void mexFunction ( /* === Parameters ======================================================= */ int nlhs, /* number of left-hand sides */ mxArray *plhs [], /* left-hand side matrices */ int nrhs, /* number of right--hand sides */ const mxArray *prhs [] /* right-hand side matrices */ ) { Zmat A; ZAMGlevelmat *PRE; ZILUPACKparam *param; integer n; const char **fnames; const mwSize *dims; mxClassID *classIDflags; mxArray *tmp, *fout, *A_input , *b_input, *x0_input, *options_input, *PRE_input, *options_output, *x_output; char *pdata, *input_buf, *output_buf; mwSize mrows, ncols, buflen, ndim,nnz; int ifield, status, nfields, ierr,i,j,k,l,m; size_t sizebuf; double dbuf, *A_valuesR, *A_valuesI, *convert, *sr, *pr, *pi; doublecomplex *sol, *rhs; mwIndex *irs, *jcs, *A_ja, /* row indices of input matrix A */ *A_ia; /* column pointers of input matrix A */ if (nrhs != 5) mexErrMsgTxt("five input arguments required."); else if (nlhs !=2) mexErrMsgTxt("Too many output arguments."); else if (!mxIsStruct(prhs[2])) mexErrMsgTxt("Third input must be a structure."); else if (!mxIsNumeric(prhs[0])) mexErrMsgTxt("First input must be a matrix."); /* The first input must be a square matrix.*/ A_input = (mxArray *) prhs [0] ; /* get size of input matrix A */ mrows = mxGetM (A_input) ; ncols = mxGetN (A_input) ; nnz = mxGetNzmax(A_input); if (mrows!=ncols) { mexErrMsgTxt("First input must be a square matrix."); } if (!mxIsSparse (A_input)) { mexErrMsgTxt ("ILUPACK: input matrix must be in sparse format.") ; } /* copy input matrix to sparse row format */ A.nc=A.nr=mrows; A.ia=(integer *) MAlloc((size_t)(A.nc+1)*sizeof(integer),"ZGNLSYMilupacksolver"); A.ja=(integer *) MAlloc((size_t)nnz *sizeof(integer),"ZGNLSYMilupacksolver"); A. a=(doublecomplex *) MAlloc((size_t)nnz *sizeof(doublecomplex), "ZGNLSYMilupacksolver"); A_ja = (mwIndex *) mxGetIr (A_input) ; A_ia = (mwIndex *) mxGetJc (A_input) ; A_valuesR = (double *) mxGetPr(A_input); if (mxIsComplex(A_input)) A_valuesI = (double *) mxGetPi(A_input); /* -------------------------------------------------------------------- */ /* .. Convert matrix from 0-based C-notation to Fortran 1-based */ /* notation. */ /* -------------------------------------------------------------------- */ /* for (i = 0 ; i < ncols ; i++) for (j = A_ia[i] ; j < A_ia[i+1] ; j++) printf("i=%d j=%d A.real=%e\n", i+1, A_ja[j]+1, A_valuesR[j]); */ for (i=0; i<=A.nr; i++) A.ia[i]=0; /* remember that MATLAB uses storage by columns and NOT by rows! */ for (i=0; i<A.nr; i++) { for (j=A_ia[i]; j<A_ia[i+1]; j++) { k=A_ja[j]; A.ia[k+1]++; } } /* now we know how many entries are located in every row */ /* switch to pointer structure */ for (i=0; i<A.nr; i++) A.ia[i+1]+=A.ia[i]; if (mxIsComplex(A_input)) { for (i=0; i<ncols; i++) { for (j=A_ia[i]; j<A_ia[i+1]; j++) { /* row index l in C-notation */ l=A_ja[j]; /* where does row l currently start */ k=A.ia[l]; /* column index will be i in FORTRAN notation */ A.ja[k]=i+1; A.a [k].r =A_valuesR[j]; A.a [k++].i=A_valuesI[j]; A.ia[l]=k; } } } else { for (i=0; i<ncols; i++) { for (j=A_ia[i]; j<A_ia[i+1]; j++) { /* row index l in C-notation */ l=A_ja[j]; /* where does row l currently start */ k=A.ia[l]; /* column index will be i in FORTRAN notation */ A.ja[k]=i+1; A.a [k].r =A_valuesR[j]; A.a [k++].i=0; A.ia[l]=k; } } } /* switch to FORTRAN style */ for (i=A.nr; i>0; i--) A.ia[i]=A.ia[i-1]+1; A.ia[0]=1; /* for (i = 0 ; i < A.nr ; i++) for (j = A.ia[i]-1 ; j < A.ia[i+1]-1 ; j++) printf("i=%d j=%d A.real=%e A.imag=%e\n", i+1, A.ja[j], A.a[j].r, A.a[j].i); */ /* import pointer to the preconditioner */ PRE_input = (mxArray*) prhs [1] ; /* get number of levels of input preconditioner structure `PREC' */ /* nlev=mxGetN(PRE_input); */ nfields = mxGetNumberOfFields(PRE_input); /* allocate memory for storing pointers */ fnames = mxCalloc((size_t)nfields, (size_t)sizeof(*fnames)); for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(PRE_input,ifield); /* check whether `PREC.ptr' exists */ if (!strcmp("ptr",fnames[ifield])) { /* field `ptr' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(&PRE, pdata, (size_t)sizeof(size_t)); } else if (!strcmp("param",fnames[ifield])) { /* field `param' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(¶m, pdata, (size_t)sizeof(size_t)); } } mxFree(fnames); /* rescale input matrix */ /* obsolete for (i=0; i <A.nr; i++) { for (j=A.ia[i]-1; j<A.ia[i+1]-1; j++) { A.a[j].r*=PRE->rowscal[i].r*PRE->colscal[A.ja[j]-1].r; A.a[j].i*=PRE->rowscal[i].r*PRE->colscal[A.ja[j]-1].r; } } */ /* Get third input argument `options' */ options_input=(mxArray*)prhs[2]; nfields = mxGetNumberOfFields(options_input); /* Allocate memory for storing classIDflags */ classIDflags = (mxClassID *) mxCalloc((size_t)nfields+1, (size_t)sizeof(mxClassID)); /* allocate memory for storing pointers */ fnames = mxCalloc((size_t)nfields+1, (size_t)sizeof(*fnames)); /* Get field name pointers */ j=-1; for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(options_input,ifield); /* check whether `options.niter' already exists */ if (!strcmp("niter",fnames[ifield])) j=ifield; } if (j==-1) fnames[nfields]="niter"; /* mexPrintf("search for niter completed\n"); fflush(stdout); */ /* import data */ for (ifield = 0; ifield < nfields; ifield++) { /* mexPrintf("%2d\n",ifield+1); fflush(stdout); */ tmp = mxGetFieldByNumber(options_input,0,ifield); classIDflags[ifield] = mxGetClassID(tmp); ndim = mxGetNumberOfDimensions(tmp); dims = mxGetDimensions(tmp); /* Create string/numeric array */ if (classIDflags[ifield] == mxCHAR_CLASS) { /* Get the length of the input string. */ buflen = (mxGetM(tmp) * mxGetN(tmp)) + 1; /* Allocate memory for input and output strings. */ input_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); /* Copy the string data from tmp into a C string input_buf. */ status = mxGetString(tmp, input_buf, buflen); if (!strcmp("amg",fnames[ifield])) { if (strcmp(param->amg,input_buf)) { param->amg=(char *)MAlloc((size_t)buflen*sizeof(char),"ilupacksolver"); strcpy(param->amg,input_buf); } } else if (!strcmp("presmoother",fnames[ifield])) { if (strcmp(param->presmoother,input_buf)) { param->presmoother=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->presmoother,input_buf); } } else if (!strcmp("postsmoother",fnames[ifield])) { if (strcmp(param->postsmoother,input_buf)) { param->postsmoother=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->postsmoother,input_buf); } } else if (!strcmp("typecoarse",fnames[ifield])) { if (strcmp(param->typecoarse,input_buf)) { param->typecoarse=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->typecoarse,input_buf); } } else if (!strcmp("typetv",fnames[ifield])) { if (strcmp(param->typetv,input_buf)) { param->typetv=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->typetv,input_buf); } } else if (!strcmp("FCpart",fnames[ifield])) { if (strcmp(param->FCpart,input_buf)) { param->FCpart=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->FCpart,input_buf); } } else if (!strcmp("solver",fnames[ifield])) { if (strcmp(param->solver,input_buf)) { param->solver=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->solver,input_buf); } } else if (!strcmp("ordering",fnames[ifield])) { if (strcmp(param->ordering,input_buf)) { param->ordering=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->ordering,input_buf); } } else { /* mexPrintf("%s ignored\n",fnames[ifield]);fflush(stdout); */ } } else { if (!strcmp("elbow",fnames[ifield])) { param->elbow=*mxGetPr(tmp); } else if (!strcmp("lfilS",fnames[ifield])) { param->lfilS=*mxGetPr(tmp); } else if (!strcmp("lfil",fnames[ifield])) { param->lfil=*mxGetPr(tmp); } else if (!strcmp("maxit",fnames[ifield])) { param->maxit=*mxGetPr(tmp); } else if (!strcmp("droptolS",fnames[ifield])) { param->droptolS=*mxGetPr(tmp); } else if (!strcmp("droptolc",fnames[ifield])) { param->droptolc=*mxGetPr(tmp); } else if (!strcmp("droptol",fnames[ifield])) { param->droptol=*mxGetPr(tmp); } else if (!strcmp("condest",fnames[ifield])) { param->condest=*mxGetPr(tmp); } else if (!strcmp("restol",fnames[ifield])) { param->restol=*mxGetPr(tmp); } else if (!strcmp("npresmoothing",fnames[ifield])) { param->npresmoothing=*mxGetPr(tmp); } else if (!strcmp("npostmoothing",fnames[ifield])) { param->npostsmoothing=*mxGetPr(tmp); } else if (!strcmp("ncoarse",fnames[ifield])) { param->ncoarse=*mxGetPr(tmp); } else if (!strcmp("matching",fnames[ifield])) { param->matching=*mxGetPr(tmp); } else if (!strcmp("nrestart",fnames[ifield])) { param->nrestart=*mxGetPr(tmp); } else if (!strcmp("damping",fnames[ifield])) { param->damping.r=*mxGetPr(tmp); if (mxIsComplex(tmp)) param->damping.i=*mxGetPi(tmp); else param->damping.i=0; } else if (!strcmp("mixedprecision",fnames[ifield])) { param->mixedprecision=*mxGetPr(tmp); } else { /* mexPrintf("%s ignored\n",fnames[ifield]);fflush(stdout); */ } } } /* copy right hand side `b' */ b_input = (mxArray *) prhs [3] ; /* get size of input matrix A */ rhs=(doublecomplex*) MAlloc((size_t)A.nr*sizeof(doublecomplex),"ZGNLSYMilupacksolver:rhs"); pr=mxGetPr(b_input); if (!mxIsComplex(b_input)) { for (i=0; i<A.nr; i++) { rhs[i].r=pr[i]; rhs[i].i=0; } } else { pi=mxGetPi(b_input); for (i=0; i<A.nr; i++) { rhs[i].r=pr[i]; rhs[i].i=pi[i]; } } /* copy initial solution `x0' */ x0_input = (mxArray *) prhs [4] ; /* numerical solution */ sol=(doublecomplex *)MAlloc((size_t)A.nr*sizeof(doublecomplex),"ZGNLSYMilupacksolver:sol"); pr=mxGetPr(x0_input); if (!mxIsComplex(x0_input)) { for (i=0; i<A.nr; i++) { sol[i].r=pr[i]; sol[i].i=0; } } else { pi=mxGetPi(x0_input); for (i=0; i<A.nr; i++) { sol[i].r=pr[i]; sol[i].i=pi[i]; } } /* set bit 2, transpose */ param->ipar[4]|=4; /* set bit 3, conjugate */ param->ipar[4]|=8; ierr=ZGNLSYMAMGsolver(&A, PRE, param, rhs, sol); /* Create a struct matrices for output */ nlhs=2; if (j==-1) plhs[1] = mxCreateStructMatrix((mwSize)1, (mwSize)1, (mwSize)nfields+1, fnames); else plhs[1] = mxCreateStructMatrix((mwSize)1, (mwSize)1, (mwSize)nfields, fnames); if (plhs[1]==NULL) mexErrMsgTxt("Could not create structure mxArray\n"); options_output=plhs[1]; /* export data */ for (ifield = 0; ifield<nfields; ifield++) { tmp = mxGetFieldByNumber(options_input,0,ifield); classIDflags[ifield] = mxGetClassID(tmp); ndim = mxGetNumberOfDimensions(tmp); dims = mxGetDimensions(tmp); /* Create string/numeric array */ if (classIDflags[ifield] == mxCHAR_CLASS) { if (!strcmp("amg",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->amg)+1, (size_t)sizeof(char)); strcpy(output_buf,param->amg); fout = mxCreateString(output_buf); } else if (!strcmp("presmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->presmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param->presmoother); fout = mxCreateString(output_buf); } else if (!strcmp("postsmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->postsmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param->postsmoother); fout = mxCreateString(output_buf); } else if (!strcmp("typecoarse",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->typecoarse)+1, (size_t)sizeof(char)); strcpy(output_buf,param->typecoarse); fout = mxCreateString(output_buf); } else if (!strcmp("typetv",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->typetv)+1, (size_t)sizeof(char)); strcpy(output_buf,param->typetv); fout = mxCreateString(output_buf); } else if (!strcmp("FCpart",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->FCpart)+1, (size_t)sizeof(char)); strcpy(output_buf,param->FCpart); fout = mxCreateString(output_buf); } else if (!strcmp("solver",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->solver)+1, (size_t)sizeof(char)); strcpy(output_buf, param->solver); fout = mxCreateString(output_buf); } else if (!strcmp("ordering",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->ordering)+1, (size_t)sizeof(char)); strcpy(output_buf, param->ordering); fout = mxCreateString(output_buf); } else { /* Get the length of the input string. */ buflen = (mxGetM(tmp) * mxGetN(tmp)) + 1; /* Allocate memory for input and output strings. */ input_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); output_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); /* Copy the string data from tmp into a C string input_buf. */ status = mxGetString(tmp, input_buf, buflen); sizebuf = (size_t)buflen*sizeof(char); memcpy(output_buf, input_buf, sizebuf); fout = mxCreateString(output_buf); } } else { /* real case */ if (mxGetPi(tmp)==NULL && strcmp("damping",fnames[ifield])) fout = mxCreateNumericArray(ndim, dims, classIDflags[ifield], mxREAL); else { /* complex case */ fout = mxCreateNumericArray(ndim, dims, classIDflags[ifield], mxCOMPLEX); } pdata = mxGetData(fout); sizebuf = mxGetElementSize(tmp); if (!strcmp("elbow",fnames[ifield])) { dbuf=param->elbow; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("lfilS",fnames[ifield])) { dbuf=param->lfilS; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("lfil",fnames[ifield])) { dbuf=param->lfil; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("maxit",fnames[ifield])) { dbuf=param->maxit; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptolS",fnames[ifield])) { dbuf=param->droptolS; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptolc",fnames[ifield])) { dbuf=param->droptolc; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptol",fnames[ifield])) { dbuf=param->droptol; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("condest",fnames[ifield])) { dbuf=param->condest; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("restol",fnames[ifield])) { dbuf=param->restol; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("npresmoothing",fnames[ifield])) { dbuf=param->npresmoothing; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("npostmoothing",fnames[ifield])) { dbuf=param->npostsmoothing; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("ncoarse",fnames[ifield])) { dbuf=param->ncoarse; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("matching",fnames[ifield])) { dbuf=param->matching; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("nrestart",fnames[ifield])) { dbuf=param->nrestart; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("damping",fnames[ifield])) { pr=mxGetPr(fout); pi=mxGetPi(fout); *pr=param->damping.r; *pi=param->damping.i; } else if (!strcmp("mixedprecision",fnames[ifield])) { dbuf=param->mixedprecision; memcpy(pdata, &dbuf, sizebuf); } else { memcpy(pdata, mxGetData(tmp), sizebuf); } } /* Set each field in output structure */ mxSetFieldByNumber(options_output, (mwIndex)0, ifield, fout); } /* store number of iteration steps */ if (j==-1) ifield=nfields; else ifield=j; fout=mxCreateDoubleMatrix((mwSize)1,(mwSize)1, mxREAL); pr=mxGetPr(fout); *pr=param->ipar[26]; /* set each field in output structure */ mxSetFieldByNumber(options_output, (mwIndex)0, ifield, fout); mxFree(fnames); mxFree(classIDflags); /* mexPrintf("options exported\n"); fflush(stdout); */ /* export approximate solution */ plhs[0] = mxCreateDoubleMatrix((mwSize)A.nr, (mwSize)1, mxCOMPLEX); x_output=plhs[0]; pr=mxGetPr(x_output); pi=mxGetPi(x_output); for (i=0; i<A.nr; i++) { pr[i]=sol[i].r; pi[i]=sol[i].i; } /* release right hand side */ free(rhs); /* release solution */ free(sol); /* release input matrix */ free(A.ia); free(A.ja); free(A.a); switch (ierr) { case 0: /* perfect! */ break; case -1: /* too many iteration steps */ mexPrintf("!!! ILUPACK Warning !!!\n"); mexPrintf("number of iteration steps exceeded its limit.\nEither increase `options.maxit'\n or recompute ILUPACK preconditioner using a smaller `options.droptol'"); break; case -2: /* weird, should not occur */ mexErrMsgTxt("not enough workspace provided."); plhs[0]=NULL; break; case -3: /* breakdown */ mexErrMsgTxt("iterative solver breaks down.\nMost likely you need to recompute ILUPACK preconditioner using a smaller `options.droptol'"); plhs[0]=NULL; break; default: /* zero pivot encountered at step number ierr */ mexPrintf("iterative solver exited with error code %d",ierr); mexErrMsgTxt("."); plhs[0]=NULL; break; } /* end switch */ return; }
/* Convert an array of MATLAB keypoint structs to a Keypoint_store. mx must be * a vector, and each struct element must have type double. */ int mx2kp(const mxArray *const mx, Keypoint_store *const kp) { const mwSize *mxDims, *coordsDims, *oriDims; mxArray *mxCoords, *mxScale, *mxOri, *mxOctave, *mxLevel; mwSize numKp, kpRows, kpCols; int i, coordsNum, scaleNum, oriNum, octaveNum, levelNum; // Verify the number of dimensions if (mxGetNumberOfDimensions(mx) != 2) return SIFT3D_FAILURE; // Parse the input dimensions mxDims = mxGetDimensions(mx); kpRows = mxDims[0]; kpCols = mxDims[1]; if (kpRows == 1) numKp = kpCols; else if (kpCols == 1) numKp = kpRows; else return SIFT3D_FAILURE; // Verify the struct size if (!mxIsStruct(mx) || mxGetNumberOfFields(mx) != kpNFields) return SIFT3D_FAILURE; // Get the field indices if ((coordsNum = mxGetFieldNumber(mx, COORDS_NAME)) < 0 || (scaleNum = mxGetFieldNumber(mx, SCALE_NAME)) < 0 || (oriNum = mxGetFieldNumber(mx, ORI_NAME)) < 0 || (octaveNum = mxGetFieldNumber(mx, OCTAVE_NAME)) < 0 || (levelNum = mxGetFieldNumber(mx, LEVEL_NAME)) < 0) return SIFT3D_FAILURE; // Get the fields of the first keypoint if ((mxCoords = mxGetFieldByNumber(mx, 0, coordsNum)) == NULL || (mxScale = mxGetFieldByNumber(mx, 0, scaleNum)) == NULL || (mxOri = mxGetFieldByNumber(mx, 0, oriNum)) == NULL || (mxOctave = mxGetFieldByNumber(mx, 0, octaveNum)) == NULL || (mxLevel = mxGetFieldByNumber(mx, 0, levelNum)) == NULL) return SIFT3D_FAILURE; // Verify the type if (!isDouble(mxCoords) || !isDouble(mxScale) || !isDouble(mxOri) || !isDouble(mxOctave) || !isDouble(mxLevel)) return SIFT3D_FAILURE; // Verify the number of dimensions if (mxGetNumberOfDimensions(mxCoords) != 2 || mxGetNumberOfDimensions(mxScale) != 2 || mxGetNumberOfDimensions(mxOri) != 2 || mxGetNumberOfDimensions(mxOctave) != 2 || mxGetNumberOfDimensions(mxLevel) != 2) return SIFT3D_FAILURE; // Verify the scalars if (!mxIsScalar(mxScale) || !mxIsScalar(mxOctave) || !mxIsScalar(mxLevel)) return SIFT3D_FAILURE; // Verify the coordinate vector dimensions coordsDims = mxGetDimensions(mxCoords); if ((coordsDims[0] != 1 && coordsDims[1] != 1) || coordsDims[0] * coordsDims[1] != IM_NDIMS) return SIFT3D_FAILURE; // Verify the orientation matrix dimensions oriDims = mxGetDimensions(mxOri); if (oriDims[0] != IM_NDIMS || oriDims[1] != IM_NDIMS) return SIFT3D_FAILURE; // Allocate space in the keypoint store if (resize_Keypoint_store(kp, (size_t) numKp)) return SIFT3D_FAILURE; // Copy the data for (i = 0; i < (int) numKp; i++) { double *coordsData; Keypoint *const key = kp->buf + i; const mwIndex idx = (mwIndex) i; // Get the matrices if ((mxCoords = mxGetFieldByNumber(mx, idx, coordsNum)) == NULL || (mxScale = mxGetFieldByNumber(mx, idx, scaleNum)) == NULL || (mxOri = mxGetFieldByNumber(mx, idx, oriNum)) == NULL || (mxOctave = mxGetFieldByNumber(mx, idx, octaveNum)) == NULL || (mxLevel = mxGetFieldByNumber(mx, idx, levelNum)) == NULL) return SIFT3D_FAILURE; // Copy the scalars key->sd = mxGetScalar(mxScale); key->o = (int) mxGetScalar(mxOctave); key->s = (int) mxGetScalar(mxLevel); // Get the coordinate data if ((coordsData = mxGetData(mxCoords)) == NULL) return SIFT3D_FAILURE; // Copy the coordinate vector key->xd = coordsData[0]; key->yd = coordsData[1]; key->zd = coordsData[2]; // Initialize the orientation matrix if (init_Mat_rm_p(&key->R, key->r_data, IM_NDIMS, IM_NDIMS, FLOAT, SIFT3D_FALSE)) return SIFT3D_FAILURE; // Copy the orientation matrix if (mx2mat(mxOri, &key->R)) return SIFT3D_FAILURE; } return SIFT3D_SUCCESS; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { //Check for proper number of inputs if(nrhs != 1) { mexErrMsgTxt("One input required\n"); } //Check for proper number of outputs bool diag_flag=false; if (nlhs == 2) { diag_flag=true; } else { if(nrhs !=1 ) { mexErrMsgTxt("One or two outputs required."); } } int nfields = mxGetNumberOfFields(prhs[0]); if(nfields!=3) { mexErrMsgTxt("First input must have three fields."); } /* Get dimensions of first field of input */ const mxArray* tmp=mxGetField(prhs[0],0,fnames_in[0]); mwSize ndims_in=mxGetNumberOfDimensions(tmp); const mwSize* dims_in=mxGetDimensions(tmp); if(!mxIsClass(tmp,"double")) { mexErrMsgTxt("First field of input must be double\n"); } int N=dims_in[ndims_in-1]; int n=1; for(int i=0;i<ndims_in-1;i++) { n*=dims_in[i]; } mexPrintf("dim n=%d number N=%d\n",n,N); double* X=(double*)mxGetData(tmp); /* Get second field of input */ tmp=mxGetField(prhs[0],0,fnames_in[1]); if(!mxIsClass(tmp,"double")) { mexErrMsgTxt("Second field of input must be double\n"); } double* ptheta=(double*)mxGetData(tmp); /* Get third field of input */ tmp=mxGetField(prhs[0],0,fnames_in[2]); if(!mxIsClass(tmp,"int32")) { mexErrMsgTxt("Third field of input must be int32\n"); } int* pmaxdescend=(int*)mxGetData(tmp); int maxdescend=(int)*pmaxdescend; /* Create matrix for the return argument. */ plhs[0] = mxCreateStructMatrix(1, 1, 8, fnames_out_0); mxArray* fout; dims[0]=1; dims[1]=1; fout =mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL); double* p=(double*)mxGetData(fout); mxSetField(plhs[0],0,fnames_out_0[0],fout); p[0]=ptheta[0]; dims[0]=1; dims[1]=8; fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL); int* params=(int*)mxGetData(fout); mxSetField(plhs[0],0,fnames_out_0[1], fout); dims[0]=2; dims[1]=N; fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL); int* plp=(int*)mxGetData(fout); mxSetField(plhs[0],0,fnames_out_0[2], fout); dims[0]=4; dims[1]=N; fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL); int* pchildren=(int*)mxGetData(fout); mxSetField(plhs[0],0,fnames_out_0[3], fout); int* pdescend_list=(int*)mxMalloc(2*N*sizeof(int)); int* pdist_flags=(int*)mxMalloc(N*sizeof(int)); int* pindices_to_dist_flags=(int*)mxMalloc(N*sizeof(int)); double* pdistances=(double*)mxMalloc(N*sizeof(double)); int* pcurrent_child_flags=(int*)mxMalloc(N*sizeof(int)); int* pindices_to_current_child_flags=(int*)mxMalloc(N*sizeof(int)); int* pcurrent_children=(int*)mxMalloc(N*sizeof(int)); Vectors vectors(n,N,X); Cover cover(*ptheta, maxdescend, &vectors,plp, pchildren, pdescend_list, pdist_flags, pindices_to_dist_flags, pdistances, pcurrent_child_flags, pindices_to_current_child_flags, pcurrent_children); params[0]=cover.getRoot(); params[1]=N; params[2]=cover.getCoverNumber(); params[3]=cover.getNumDuplicates(); params[4]=cover.getMinLevel(); params[5]=cover.getMaxLevel(); int numlevels=cover.getNumLevels(); params[6]=numlevels; params[7]=cover.getMaxDescend(); dims[0]=1; dims[1]=cover.getNumLevels(); fout=mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL); double* pradii=(double*)mxGetData(fout); pradii[0]=cover.getRadius(); for(int i=1;i<numlevels;i++) { pradii[i]=ptheta[0]*pradii[i-1]; } mxSetField(plhs[0],0,fnames_out_0[4], fout); //mexPrintf("cover.getDistCounter=%d\n",cover.getDistCtr()); dims[0]=1; dims[1]=numlevels; fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL); int* plevel_counters=(int*)mxGetData(fout); mxSetField(plhs[0],0,fnames_out_0[5], fout); dims[0]=1; dims[1]=numlevels; fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL); int* plevel_offsets=(int*)mxGetData(fout); mxSetField(plhs[0],0,fnames_out_0[6], fout); dims[0]=1; dims[1]=cover.getCoverNumber(); fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL); int* plevels=(int*)mxGetData(fout); mxSetField(plhs[0],0,fnames_out_0[7], fout); Levels(&cover,plevel_counters,plevel_offsets,plevels); if(diag_flag) { double* p=0; plhs[1]= mxCreateStructMatrix(1, 1, 4, fnames_out_1); ndims=2; dims[0]=1; dims[1]=1; fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL); p=(double*)mxGetData(fout); mxSetField(plhs[1],0,fnames_out_1[0],fout); p[0]=cover.getDistNCallsToGet(); fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL); p=(double*)mxGetData(fout); mxSetField(plhs[1],0,fnames_out_1[1],fout); p[0]=cover.getDistNCallsToSet(); fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL); p=(double*)mxGetData(fout); mxSetField(plhs[1],0,fnames_out_1[2],fout); p[0]=cover.getChildrenNCallsToGet(); fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL); p=(double*)mxGetData(fout); mxSetField(plhs[1],0,fnames_out_1[3],fout); p[0]=cover.getChildrenNCallsToSet(); } mxFree(pdescend_list); mxFree(pdist_flags); mxFree(pindices_to_dist_flags); mxFree(pdistances); mxFree(pcurrent_child_flags); mxFree(pindices_to_current_child_flags); mxFree(pcurrent_children); }
MP_Dict_c * mp_create_dict_from_mxDict(const mxArray *mxDict) { const char *func = "mp_create_dict_from_mxDict"; const char *fieldName; map<string,string,mp_ltstring> *paramMap; MP_Dict_c *dict = NULL; mxArray *mxBlockCell,*mxBlock,*mxTmp; mwSize mwNumDimension; const mwSize *mwDimension; size_t numFields; int nBlocks; int iIndexDimension,iDimension; char *fieldValue; double *dTable = NULL; string szDataString,szReturnString; if (NULL==mxDict) { mp_error_msg(func,"input is NULL\n"); return(NULL); } // Check that the input dictionary structure has the right fields mxBlockCell = mxGetField(mxDict,0,"block"); if (NULL==mxBlockCell) { mp_error_msg(func,"the dict.block field is missing\n"); return(NULL); } nBlocks = (int)mxGetNumberOfElements(mxBlockCell); if (0==nBlocks) { mp_error_msg(func,"the number of blocks should be at least one\n"); return(NULL); } if(!mxIsCell(mxBlockCell)) { mp_error_msg(func,"the dict.block is not a cell array\n"); return(NULL); } // Reach all blocks for (int i = 0; i < nBlocks; i++ ) { mxBlock = mxGetCell(mxBlockCell,i); if (NULL==mxBlock) { // This should never happen mp_error_msg(func,"dict.block{%d} could not be retrieved\n",i+1); // Clean the house if(NULL!=dict) delete dict; return(NULL); } numFields = mxGetNumberOfFields(mxBlock); if (0==numFields) { mp_error_msg(func,"the number of fields %d should be at least one in dict.block{%d}\n",numFields,i+1); // Clean the house if(NULL!=dict) delete dict; return(NULL); } // Reach all fields of the block and put them in a map paramMap = new map<string, string, mp_ltstring>(); if(NULL==paramMap) { mp_error_msg(func,"could not allocate paramMap\n"); // Clean the house if(NULL!=dict) delete dict; return(NULL); } for (unsigned int j= 0; j <numFields ; j++) { fieldName = mxGetFieldNameByNumber(mxBlock,j); if (fieldName == NULL) { mp_error_msg(func,"field number %d in dict.block{%d} could not be retrieved\n",j+1,i+1); // Clean the house if(NULL!=dict) delete dict; return(NULL); } // Retrieve the field value mxTmp = mxGetField(mxBlock,0,fieldName); if(mxTmp == NULL) { mp_error_msg(func,"value of field number %d in dict.block{%d} could not be retrieved\n",j+1,i+1); // Clean the house if(NULL!=dict) delete dict; return(NULL); } if(mxIsDouble(mxTmp)) { // Retrieve the dimension of the double mwNumDimension = mxGetNumberOfDimensions(mxTmp); mwDimension = mxGetDimensions(mxTmp); iDimension = 1; for(iIndexDimension = 0; iIndexDimension < (int)mwNumDimension; iIndexDimension++) iDimension *= mwDimension[iIndexDimension]; // Add the dimension of a double iDimension = iDimension * sizeof(double); // Getting the storage field if((dTable = (MP_Real_t*)malloc(iDimension)) == NULL) { mp_error_msg(func,"The double storage has not been allocaed\n"); return(NULL); } // Loading the mxArray if(!mp_get_anywave_datas_from_mxAnywaveTable(mxBlock,dTable)) { mp_error_msg(func,"A double value has been found but could not be retrieved\n"); // Clean the house if(NULL!=dict) delete dict; return(NULL); } // Store it in the map and free (*paramMap)["doubledata"] = string((char *)dTable, iDimension); } else { fieldValue = mxArrayToString(mxTmp); if(fieldValue == NULL) { mp_error_msg(func,"string value of field number %d in dict.block{%d} could not be retrieved\n",j+1,i+1); // Clean the house if(NULL!=dict) delete dict; return(NULL); } // Store it in the map and free (*paramMap)[string(fieldName)]=string(fieldValue); mxFree(fieldValue); fieldValue = NULL; } } // Retrieve the block creator MP_Block_c* (*blockCreator)( MP_Signal_c *setSignal, map<string, string, mp_ltstring> * paramMap ) = NULL; blockCreator = MP_Block_Factory_c::get_block_creator((*paramMap)["type"].c_str()); if (NULL == blockCreator) { mp_error_msg(func,"the block factory does not contain type %s of dict.block{%d}\n",(*paramMap)["type"].c_str(),i+1); // Clean the house if(NULL!=dict) delete dict; delete paramMap; return(NULL); } // Create the block MP_Block_c *block = blockCreator(NULL, paramMap); if (NULL == block) { mp_error_msg(func,"the dict.block{%d}, of type %s was not successfully created\n",i+1,(*paramMap)["type"].c_str()); // Clean the house if(NULL!=dict) delete dict; delete paramMap; return(NULL); } // Create the dictionary if needed (i.e. when adding first block) if (NULL==dict) { dict = MP_Dict_c::init(); if (NULL==dict) { mp_error_msg(func,"Failed to create an empty dictionary\n"); delete paramMap; delete block; return(NULL); } } // Add the block to the dictionary dict->add_block(block); if(dTable) free(dTable); delete paramMap; } return(dict); }
void mexFunction ( /* === Parameters ======================================================= */ int nlhs, /* number of left-hand sides */ mxArray *plhs [], /* left-hand side matrices */ int nrhs, /* number of right--hand sides */ const mxArray *prhs [] /* right-hand side matrices */ ) { Zmat A; ZAMGlevelmat *PRE; CAMGlevelmat *SPRE; ZILUPACKparam *param; const char **fnames; /* pointers to field names */ mxClassID *classIDflags; mxArray *tmp, *PRE_input; mwSize ndim, buflen; char *pdata, *input_buf; int ifield, status, nfields; size_t mrows, ncols, sizebuf; double dbuf; if (nrhs != 1) mexErrMsgTxt("One input arguments required."); else if (nlhs > 0) mexErrMsgTxt("No output arguments."); else if (!mxIsStruct(prhs[0])) mexErrMsgTxt("Input must be a structure."); /* import pointer to the preconditioner */ PRE_input = (mxArray*) prhs [0] ; /* get number of levels of input preconditioner structure `PREC' */ /* nlev=mxGetN(PRE_input); */ nfields = mxGetNumberOfFields(PRE_input); /* allocate memory for storing pointers */ fnames = mxCalloc((size_t)nfields, (size_t)sizeof(*fnames)); for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(PRE_input,ifield); /* check whether `PREC.ptr' exists */ if (!strcmp("ptr",fnames[ifield])) { /* field `ptr' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(&PRE, pdata, (size_t)sizeof(size_t)); } else if (!strcmp("param",fnames[ifield])) { /* field `param' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(¶m, pdata, (size_t)sizeof(size_t)); } else if (!strcmp("n",fnames[ifield])) { /* get size of the initial system */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); A.nr=A.nc=*mxGetPr(tmp); A.ia=A.ja=NULL; A.a=NULL; } } mxFree(fnames); /* finally release memory of the preconditioner */ ZGNLAMGdelete(&A,PRE,param); return; }