void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { params p; pwork *mywork; mxArray *xm; int i = 0; int j = 0; double *ptr; int numerr = 0; mxArray *outvar; mxArray *tinfos; /* change number of infofields according to profiling setting */ #if PROFILING > 0 #define NINFOFIELDS 15 #else #define NINFOFIELDS 14 #endif const char *infofields[NINFOFIELDS] = { "pcost", "dcost", "pres", "dres", "pinf", "dinf", "pinfres", "dinfres", "gap", "relgap", "r0", "numerr", "iter", "infostring" #if PROFILING > 0 ,"timing" #endif }; #if PROFILING == 1 #define NTFIELDS 3 const char *tinfo[NTFIELDS] = {"runtime", "tsolve", "tsetup"}; #endif #if PROFILING == 2 #define NTFIELDS 8 const char *tinfo[NTFIELDS] = {"runtime", "tsolve", "tsetup", "tkktcreate", "tkktfactor", "tkktsolve", "torder", "ttranspose"}; #endif #ifdef MEXARGMUENTCHECKS if( !(nrhs == 1) ) { mexErrMsgTxt("scooper only takes 1 argument: scooper(params)"); } if( nlhs > 2 ) mexErrMsgTxt("scooper has up to 2 output arguments only"); #endif xm = mxGetField(prhs[0], 0, "A"); if (xm == NULL) { mexErrMsgTxt("could not find params.A"); } else { if (!( (mxGetM(xm) == 1) && (mxGetN(xm) == 2) )) mexErrMsgTxt("A must be size (1, 2)\n"); if (mxIsComplex(xm)) mxErrMsgTxt("parameter A must be real\n"); if (!mxIsClass(xm, "double")) mxErrMsgTxt("parameter A must be full matrix of doubles"); if (mxIsSparse(xm)) mxErrMsgTxt("parameter A must be full matrix"); ptr = mxGetPr(xm); for(j = 0; j < 2; ++j) { for(i = 0; i < 1; ++i) { p.A[i][j] = *ptr++; } } } xm = mxGetField(prhs[0], 0, "b"); if (xm == NULL) { mexErrMsgTxt("could not find params.b"); } else { if (!( (mxGetM(xm) == 1) && (mxGetN(xm) == 1) )) mexErrMsgTxt("b must be size (1, 1)\n"); if (mxIsComplex(xm)) mxErrMsgTxt("parameter b must be real\n"); if (!mxIsClass(xm, "double")) mxErrMsgTxt("parameter b must be full vector of doubles"); if (mxIsSparse(xm)) mxErrMsgTxt("parameter b must be full vector"); p.b = *mxGetPr(xm); } xm = mxGetField(prhs[0], 0, "ct"); if (xm == NULL) { mexErrMsgTxt("could not find params.ct"); } else { if (!( (mxGetM(xm) == 1) && (mxGetN(xm) == 2) )) mexErrMsgTxt("ct must be size (1, 2)\n"); if (mxIsComplex(xm)) mxErrMsgTxt("parameter ct must be real\n"); if (!mxIsClass(xm, "double")) mxErrMsgTxt("parameter ct must be full matrix of doubles"); if (mxIsSparse(xm)) mxErrMsgTxt("parameter ct must be full matrix"); ptr = mxGetPr(xm); for(j = 0; j < 2; ++j) { for(i = 0; i < 1; ++i) { p.ct[i][j] = *ptr++; } } } mywork = setup(&p); if(mywork == NULL) { mexErrMsgTxt("Internal problem occurred in ECOS while setting up the problem.\nPlease send a bug report with data to Alexander Domahidi.\nEmail: [email protected]"); } int flag = 0; flag = solve(mywork, &v); const int num_var_names = 1; const char *var_names[] = {"x"}; plhs[0] = mxCreateStructMatrix(1, 1, num_var_names, var_names); xm = mxCreateDoubleMatrix(2, 1,mxREAL); mxSetField(plhs[0], 0, "x", xm); memcpy(mxGetPr(xm), v.x, sizeof(double)*2); if( nlhs == 2 ){ plhs[1] = mxCreateStructMatrix(1, 1, NINFOFIELDS, infofields); /* 1. primal objective */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = 1.0*((double)mywork->info->pcost); mxSetField(plhs[1], 0, "pcost", outvar); /* 2. dual objective */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->dcost; mxSetField(plhs[1], 0, "dcost", outvar); /* 3. primal residual */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->pres; mxSetField(plhs[1], 0, "pres", outvar); /* 4. dual residual */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->dres; mxSetField(plhs[1], 0, "dres", outvar); /* 5. primal infeasible? */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->pinf; mxSetField(plhs[1], 0, "pinf", outvar); /* 6. dual infeasible? */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->dinf; mxSetField(plhs[1], 0, "dinf", outvar); /* 7. primal infeasibility measure */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->pinfres; mxSetField(plhs[1], 0, "pinfres", outvar); /* 8. dual infeasibility measure */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->dinfres; mxSetField(plhs[1], 0, "dinfres", outvar); /* 9. duality gap */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->gap; mxSetField(plhs[1], 0, "gap", outvar); /* 10. relative duality gap */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->relgap; mxSetField(plhs[1], 0, "relgap", outvar); /* 11. feasibility tolerance??? */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->stgs->feastol; mxSetField(plhs[1], 0, "r0", outvar); /* 12. iterations */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->iter; mxSetField(plhs[1], 0, "iter", outvar); /* 13. infostring */ switch( flag ){ case ECOS_OPTIMAL: outvar = mxCreateString("Optimal solution found"); break; case ECOS_MAXIT: outvar = mxCreateString("Maximum number of iterations reached"); break; case ECOS_PINF: outvar = mxCreateString("Primal infeasible"); break; case ECOS_DINF: outvar = mxCreateString("Dual infeasible"); break; case ECOS_KKTZERO: outvar = mxCreateString("Element of D zero during KKT factorization"); break; case ECOS_OUTCONE: outvar = mxCreateString("PROBLEM: Mulitpliers leaving the cone"); break; default: outvar = mxCreateString("UNKNOWN PROBLEM IN SOLVER"); } mxSetField(plhs[1], 0, "infostring", outvar); #if PROFILING > 0 /* 14. timing information */ tinfos = mxCreateStructMatrix(1, 1, NTFIELDS, tinfo); /* 14.1 --> runtime */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->tsolve + (double)mywork->info->tsetup; mxSetField(tinfos, 0, "runtime", outvar); /* 14.2 --> setup time */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->tsetup; mxSetField(tinfos, 0, "tsetup", outvar); /* 14.3 --> solve time */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->tsolve; mxSetField(tinfos, 0, "tsolve", outvar); #if PROFILING > 1 /* 14.4 time to create KKT matrix */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->tkktcreate; mxSetField(tinfos, 0, "tkktcreate", outvar); /* 14.5 time for kkt solve */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->tkktsolve; mxSetField(tinfos, 0, "tkktsolve", outvar); /* 14.6 time for kkt factor */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->tfactor; mxSetField(tinfos, 0, "tkktfactor", outvar); /* 14.7 time for ordering */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->torder; mxSetField(tinfos, 0, "torder", outvar); /* 14.8 time for transposes */ outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)mywork->info->ttranspose; mxSetField(tinfos, 0, "ttranspose", outvar); #endif mxSetField(plhs[1], 0, "timing", tinfos); #endif /* 15. numerical error? */ if( (flag == ECOS_NUMERICS) || (flag == ECOS_OUTCONE) || (flag == ECOS_FATAL) ){ numerr = 1; } outvar = mxCreateDoubleMatrix(1, 1, mxREAL); *mxGetPr(outvar) = (double)numerr; mxSetField(plhs[1], 0, "numerr", outvar); } cleanup(mywork); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // This function is called like: scaledData = scaledDoubleAnalogDataFromRaw(dataAsADCCounts, channelScales, scalingCoefficients) // Function to convert raw ADC data as int16s to doubles, taking to the // per-channel scaling factors into account. // // scalingCoefficients: nScans x nChannels int16 array // channelScales: 1 x nChannels double array, each element having // (implicit) units of V/(native unit), where each // channel has its own native unit. // scalingCoefficients: nCoefficients x nChannels double array, // contains scaling coefficients for converting // ADC counts to volts at the ADC input. Row 1 // is the constant terms, row 2 the linear, // row 3 quadratic, etc. // // scaledData: nScans x nChannels double array containing the scaled // data, each channel with it's own native unit. // Load in the arguments, checking them thoroughly // prhs[0]: dataAsADCCounts if ( mxIsClass(prhs[0], "int16") && mxGetNumberOfDimensions(prhs[0])==2 ) { // all is well } else { mexErrMsgIdAndTxt("ws:scaledDoubleAnalogDataFromRawMex:scalingCoefficientsNotRight", "Argument scalingCoefficients must be an int16 matrix"); } mwSize nScans = mxGetM(prhs[0]) ; mwSize nChannels = mxGetN(prhs[0]) ; int16_t* dataAsADCCounts = (int16_t *) mxGetData(prhs[0]) ; // "Convert" to a C++ array, although still in col-major order // prhs[1]: channelScales if (mxIsDouble(prhs[1]) && !mxIsComplex(prhs[1]) && mxGetNumberOfDimensions(prhs[1])==2 && mxGetN(prhs[1])==nChannels) { // all is well } else { mexErrMsgIdAndTxt("ws:scaledDoubleAnalogDataFromRawMex:channelScalesNotRight", "Argument channelScales must be a non-complex double row vector with the same number of columns as dataAsADCCounts."); } double *channelScales = mxGetPr(prhs[1]); // "Convert" to a C++ array // prhs[2]: scalingCoefficients if (mxIsDouble(prhs[2]) && !mxIsComplex(prhs[2]) && mxGetNumberOfDimensions(prhs[2])==2 && mxGetN(prhs[2])==nChannels) { // all is well } else { mexErrMsgIdAndTxt("ws:scaledDoubleAnalogDataFromRawMex:scalingCoefficientsNotRight", "Argument scalingCoefficients must be a non-complex double matrix with the same number of columns as dataAsADCCounts."); } mwSize nCoefficients = mxGetM(prhs[2]) ; double *scalingCoefficients = mxGetPr(prhs[2]) ; // "Convert" to a C++ array, although still in col-major order // At this point, all args have been read and validated // even if nlhs==0, still safe to assign to plhs[0], and should do this, so ans gets assigned plhs[0] = mxCreateDoubleMatrix(nScans, nChannels, mxREAL) ; double* scaledData = mxGetPr(plhs[0]) ; // For each element of dataAsADCCounts, pass it through the polynominal function defined by the scaling coefficients for that channel, // and set the corresponding element of scaledData int16_t* source = dataAsADCCounts ; // source points to the current element of the "source" array, dataAsADCCounts if (nCoefficients==0) { // If no coeffs, the "polynominal" always evals to zero for (mwIndex j=0; j<nChannels; ++j) { double thisChannelScale = channelScales[j] ; const double datumAsADCVoltage = 0 ; double scaledDatum = datumAsADCVoltage/thisChannelScale ; double *targetStart = scaledData + j*nScans ; // pointer for first target element for this channel double *targetEnd = targetStart + nScans ; // pointer just pasty for last target element for this channel for (double *target = targetStart; target<targetEnd; target++) { *target = scaledDatum ; } } } else if (nCoefficients==1) { // If one coeff, the polynominal always evals to a constant for (mwIndex j=0; j<nChannels; ++j) { const double thisChannelScale = channelScales[j] ; // Get the scaling factor for this channel, which is actually completely separate from the scaling coefficients // This is the scaling factor to convert from volts at the BNC to whatever the units of the actual measurment are. // The "scaling coefficients" define how to convert from "counts" at the ADC to volts at the BNC. const double* scalingCoefficientsForThisChannel = scalingCoefficients + j*nCoefficients ; const double c0 = scalingCoefficientsForThisChannel[0] ; const double y = c0 ; const double scaledDatum = y/thisChannelScale ; double *targetStart = scaledData + j*nScans ; // pointer for first target element for this channel const double *targetEnd = targetStart + nScans ; // pointer just pasty for last target element for this channel for (double *target = targetStart; target<targetEnd; target++) { const double x = double(*source) ; // Do the whole business to efficiently evaluate a polynomial *target = scaledDatum ; } } } else if (nCoefficients==2) { for (mwIndex j=0; j<nChannels; ++j) { const double thisChannelScale = channelScales[j] ; // Get the scaling factor for this channel, which is actually completely separate from the scaling coefficients // This is the scaling factor to convert from volts at the BNC to whatever the units of the actual measurment are. // The "scaling coefficients" define how to convert from "counts" at the ADC to volts at the BNC. const double* scalingCoefficientsForThisChannel = scalingCoefficients + j*nCoefficients ; const double c0 = scalingCoefficientsForThisChannel[0] ; const double c1 = scalingCoefficientsForThisChannel[1] ; double *targetStart = scaledData + j*nScans ; // pointer for first target element for this channel const double *targetEnd = targetStart + nScans ; // pointer just pasty for last target element for this channel for (double *target = targetStart; target<targetEnd; target++) { const double x = double(*source) ; // Do the whole business to efficiently evaluate a polynomial const double y = c0 + x*c1 ; const double scaledDatum = y/thisChannelScale ; *target = scaledDatum ; // Advance the source pointer once, since the source and target elements are one-to-one ++source ; } } } else if (nCoefficients==3) { for (mwIndex j=0; j<nChannels; ++j) { const double thisChannelScale = channelScales[j] ; // Get the scaling factor for this channel, which is actually completely separate from the scaling coefficients // This is the scaling factor to convert from volts at the BNC to whatever the units of the actual measurment are. // The "scaling coefficients" define how to convert from "counts" at the ADC to volts at the BNC. const double* scalingCoefficientsForThisChannel = scalingCoefficients + j*nCoefficients ; const double c0 = scalingCoefficientsForThisChannel[0] ; const double c1 = scalingCoefficientsForThisChannel[1] ; const double c2 = scalingCoefficientsForThisChannel[2] ; double *targetStart = scaledData + j*nScans ; // pointer for first target element for this channel const double *targetEnd = targetStart + nScans ; // pointer just pasty for last target element for this channel for (double *target = targetStart; target<targetEnd; target++) { const double x = double(*source) ; // Do the whole business to efficiently evaluate a polynomial const double y = c0 + x*(c1 + x*c2) ; const double scaledDatum = y/thisChannelScale ; *target = scaledDatum ; // Advance the source pointer once, since the source and target elements are one-to-one ++source ; } } } else if (nCoefficients==4) { for (mwIndex j=0; j<nChannels; ++j) { const double thisChannelScale = channelScales[j] ; // Get the scaling factor for this channel, which is actually completely separate from the scaling coefficients // This is the scaling factor to convert from volts at the BNC to whatever the units of the actual measurment are. // The "scaling coefficients" define how to convert from "counts" at the ADC to volts at the BNC. const double* scalingCoefficientsForThisChannel = scalingCoefficients + j*nCoefficients ; const double c0 = scalingCoefficientsForThisChannel[0] ; const double c1 = scalingCoefficientsForThisChannel[1] ; const double c2 = scalingCoefficientsForThisChannel[2] ; const double c3 = scalingCoefficientsForThisChannel[3] ; double *targetStart = scaledData + j*nScans ; // pointer for first target element for this channel const double *targetEnd = targetStart + nScans ; // pointer just pasty for last target element for this channel for (double *target = targetStart; target<targetEnd; target++) { const double x = double(*source) ; // Do the whole business to efficiently evaluate a polynomial const double y = c0 + x*(c1 + x*(c2 + x*c3) ) ; const double scaledDatum = y/thisChannelScale ; *target = scaledDatum ; // Advance the source pointer once, since the source and target elements are one-to-one ++source ; } } } else { // if get here nCoefficients>=5 for (mwIndex j=0; j<nChannels; ++j) { double thisChannelScale = channelScales[j] ; // Get the scaling factor for this channel, which is actually completely separate from the scaling coefficients // This is the scaling factor to convert from volts at the BNC to whatever the units of the actual measurment are. // The "scaling coefficients" define how to convert from "counts" at the ADC to volts at the BNC. double* scalingCoefficientsForThisChannel = scalingCoefficients + j*nCoefficients ; double* pointerToHighestOrderCoefficient = scalingCoefficientsForThisChannel + (nCoefficients-1) ; double highestOrderCoefficient = *(pointerToHighestOrderCoefficient) ; double *targetStart = scaledData + j*nScans ; // pointer for first target element for this channel double *targetEnd = targetStart + nScans ; // pointer just pasty for last target element for this channel for (double *target = targetStart; target<targetEnd; target++) { double datumAsADCCounts = double(*source) ; // Do the whole business to efficiently evaluate a polynomial double temp = highestOrderCoefficient ; for ( double* pointerToCurrentCoefficient = pointerToHighestOrderCoefficient-1 ; pointerToCurrentCoefficient>=scalingCoefficientsForThisChannel ; --pointerToCurrentCoefficient ) { double thisCoefficient = *pointerToCurrentCoefficient ; temp = thisCoefficient + datumAsADCCounts * temp ; } double datumAsADCVoltage = temp ; // compiler should eliminate this... double scaledDatum = datumAsADCVoltage/thisChannelScale ; *target = scaledDatum ; // Advance the source pointer once, since the source and target elements are one-to-one ++source ; } } } // plhs[0] should have all its elements filled with rich, savory, properly-scaled data at this point, so exit }
void mexFunction(int nlhs, /* No. of output arguments */ mxArray *plhs[], /* Output arguments. */ int nrhs, /* No. of input arguments. */ const mxArray *prhs[]) /* Input arguments. */ { int ndim, wmap_ndim, krn_ndim; int n, i; const int *cdim = NULL, *wmap_cdim = NULL, *krn_cdim = NULL; unsigned int dim[3], kdim[3]; double *pm = NULL; double *wmap = NULL; double *opm = NULL; double *krnl = NULL; if (nrhs == 0) mexErrMsgTxt("usage: pm = pm_pad(pm,wmap,kernel)"); if (nrhs != 3) mexErrMsgTxt("pm_smooth_phasemap_dtj: 3 input arguments required"); if (nlhs != 1) mexErrMsgTxt("pm_smooth_phasemap_dtj: 1 output argument required"); /* Get phase map. */ if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0])) { mexErrMsgTxt("pm_smooth_phasemap_dtj: pm must be numeric, real, full and double"); } ndim = mxGetNumberOfDimensions(prhs[0]); if ((ndim < 2) | (ndim > 3)) { mexErrMsgTxt("pm_smooth_phasemap_dtj: pm must be 2 or 3-dimensional"); } cdim = mxGetDimensions(prhs[0]); pm = mxGetPr(prhs[0]); /* Get weight-map (reciprocal of variance). */ if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) { mexErrMsgTxt("pm_smooth_phasemap_dtj: wmap must be numeric, real, full and double"); } wmap_ndim = mxGetNumberOfDimensions(prhs[1]); if (wmap_ndim != ndim) { mexErrMsgTxt("pm_smooth_phasemap_dtj: pm and wmap must have same dimensionality"); } wmap_cdim = mxGetDimensions(prhs[1]); for (i=0; i<ndim; i++) { if (cdim[i] != wmap_cdim[i]) { mexErrMsgTxt("pm_smooth_phasemap_dtj: pm and wmap must have same size"); } } wmap = mxGetPr(prhs[1]); /* Fix dimensions to allow for 2D and 3D data. */ dim[0]=cdim[0]; dim[1]=cdim[1]; if (ndim==2) { dim[2]=1; ndim=3; } else { dim[2]=cdim[2]; } for (i=0, n=1; i<ndim; i++) { n *= dim[i]; } /* Get kernel */ if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2])) { mexErrMsgTxt("pm_smooth_phasemap_dtj: kernel must be numeric, real, full and double"); } krn_ndim = mxGetNumberOfDimensions(prhs[2]); if (krn_ndim != ndim) { mexErrMsgTxt("pm_smooth_phasemap_dtj: pm and kernel must have same dimensionality"); } krn_cdim = mxGetDimensions(prhs[2]); krnl = mxGetPr(prhs[2]); kdim[0]=krn_cdim[0]; kdim[1]=krn_cdim[1]; if (krn_ndim==2) { kdim[2]=1; krn_ndim=3; } else { kdim[2]=krn_cdim[2]; } /* Allocate mem for smoothed output phasemap. */ plhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(prhs[0]), mxGetDimensions(prhs[0]),mxDOUBLE_CLASS,mxREAL); opm = mxGetPr(plhs[0]); smooth(pm,wmap,dim,krnl,kdim,opm); return; }
void mexFunction(int nlhs_m, mxArray *plhs_m[], int nrhs_m, const mxArray *prhs_m[]) { int i; char * jobz; char * range; char * uplo; int * n; double * a; int * lda; double * vl; double * vu; int * il; int * iu; double * abstol; int * m; double * w; double * z; int * ldz; double * work; int * lwork; double * rwork; int * iwork; int * ifail; int * info; plhs_m[3]=mxDuplicateArray(prhs_m[3]); n=(int *)mxGetPr(plhs_m[3]); plhs_m[5]=mxDuplicateArray(prhs_m[5]); lda=(int *)mxGetPr(plhs_m[5]); plhs_m[8]=mxDuplicateArray(prhs_m[8]); il=(int *)mxGetPr(plhs_m[8]); plhs_m[9]=mxDuplicateArray(prhs_m[9]); iu=(int *)mxGetPr(plhs_m[9]); plhs_m[11]=mxDuplicateArray(prhs_m[11]); m=(int *)mxGetPr(plhs_m[11]); plhs_m[14]=mxDuplicateArray(prhs_m[14]); ldz=(int *)mxGetPr(plhs_m[14]); plhs_m[16]=mxDuplicateArray(prhs_m[16]); lwork=(int *)mxGetPr(plhs_m[16]); plhs_m[20]=mxDuplicateArray(prhs_m[20]); info=(int *)mxGetPr(plhs_m[20]); plhs_m[0] = mxDuplicateArray(prhs_m[0]); jobz = (char*) mxArrayToString(plhs_m[0]); plhs_m[1] = mxDuplicateArray(prhs_m[1]); range = (char*) mxArrayToString(plhs_m[1]); plhs_m[2] = mxDuplicateArray(prhs_m[2]); uplo = (char*) mxArrayToString(plhs_m[2]); a=malloc((*lda)*(* n)*2*sizeof(double)); for (i=0; i<(*lda)*(* n); i++) { a[i*2]=(mxGetPr(prhs_m[4]))[i]; if (mxIsComplex(prhs_m[4])) a[i*2+1]=(mxGetPi(prhs_m[4]))[i]; else a[i*2+1]=0; } plhs_m[6]=mxDuplicateArray(prhs_m[6]); vl = mxGetPr(plhs_m[6]); plhs_m[7]=mxDuplicateArray(prhs_m[7]); vu = mxGetPr(plhs_m[7]); plhs_m[10]=mxDuplicateArray(prhs_m[10]); abstol = mxGetPr(plhs_m[10]); plhs_m[12]=mxDuplicateArray(prhs_m[12]); w = mxGetPr(plhs_m[12]); z=malloc((*ldz)*( max(1,*n))*2*sizeof(double)); for (i=0; i<(*ldz)*( max(1,*n)); i++) { z[i*2]=(mxGetPr(prhs_m[13]))[i]; if (mxIsComplex(prhs_m[13])) z[i*2+1]=(mxGetPi(prhs_m[13]))[i]; else z[i*2+1]=0; } work=malloc((max(1,*lwork))*(1)*2*sizeof(double)); for (i=0; i<(max(1,*lwork))*(1); i++) { work[i*2]=(mxGetPr(prhs_m[15]))[i]; if (mxIsComplex(prhs_m[15])) work[i*2+1]=(mxGetPi(prhs_m[15]))[i]; else work[i*2+1]=0; } plhs_m[17]=mxDuplicateArray(prhs_m[17]); rwork = mxGetPr(plhs_m[17]); plhs_m[18]=mxDuplicateArray(prhs_m[18]); iwork = (int *) mxGetPr(plhs_m[18]); plhs_m[19]=mxDuplicateArray(prhs_m[19]); ifail = (int *) mxGetPr(plhs_m[19]); #ifdef F77_INT F77_INT* F77_n = n , F77_lda = lda , F77_il = il , F77_iu = iu , F77_m = m , F77_ldz = ldz , F77_lwork = lwork , F77_iwork = iwork , F77_ifail = ifail , F77_info = info ; #else #define F77_n n #define F77_lda lda #define F77_il il #define F77_iu iu #define F77_m m #define F77_ldz ldz #define F77_lwork lwork #define F77_iwork iwork #define F77_ifail ifail #define F77_info info #endif #ifdef F77_CHAR F77_CHAR* F77_jobz = jobz , F77_range = range , F77_uplo = uplo ; #else #define F77_jobz jobz #define F77_range range #define F77_uplo uplo #endif f77_zheevx(F77_jobz, F77_range, F77_uplo, F77_n, a, F77_lda, vl, vu, F77_il, F77_iu, abstol, F77_m, w, z, F77_ldz, work, F77_lwork, rwork, F77_iwork, F77_ifail, F77_info); plhs_m[4] = mxCreateDoubleMatrix((*lda),(* n),mxCOMPLEX); for (i=0; i<(*lda)*(* n); i++) { (mxGetPr(plhs_m[4]))[i]=a[2*i]; if (mxIsComplex(plhs_m[4])) (mxGetPi(plhs_m[4]))[i]=a[2*i+1]; } plhs_m[13] = mxCreateDoubleMatrix((*ldz),( max(1,*n)),mxCOMPLEX); for (i=0; i<(*ldz)*( max(1,*n)); i++) { (mxGetPr(plhs_m[13]))[i]=z[2*i]; if (mxIsComplex(plhs_m[13])) (mxGetPi(plhs_m[13]))[i]=z[2*i+1]; } plhs_m[15] = mxCreateDoubleMatrix((max(1,*lwork)),(1),mxCOMPLEX); for (i=0; i<(max(1,*lwork))*(1); i++) { (mxGetPr(plhs_m[15]))[i]=work[2*i]; if (mxIsComplex(plhs_m[15])) (mxGetPi(plhs_m[15]))[i]=work[2*i+1]; } return; }
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[] = {"v", "w"}; const int num_var_names = 2; /* 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, "Y"); if (xm == NULL) { printf("could not find params.Y.\n"); } else { if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 8))) { printf("Y must be size (3,8), not (%d,%d).\n", mxGetM(xm), mxGetN(xm)); this_var_errors++; } if (mxIsComplex(xm)) { printf("parameter Y must be real.\n"); this_var_errors++; } if (!mxIsClass(xm, "double")) { printf("parameter Y must be a full matrix of doubles.\n"); this_var_errors++; } if (mxIsSparse(xm)) { printf("parameter Y must be a full matrix.\n"); this_var_errors++; } if (this_var_errors == 0) { dest = params.Y; src = mxGetPr(xm); for (i = 0; i < 24; i++) *dest++ = *src++; valid_vars++; } } if (valid_vars != 1) { printf("Error: %d parameters are invalid.\n", 1 - 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 < 24; i++) printf(" params.Y[%d] = %.6g;\n", i, params.Y[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(3, 1, mxREAL); mxSetField(plhs[0], 0, "v", xm); dest = mxGetPr(xm); src = vars.v; for (i = 0; i < 3; i++) { *dest++ = *src++; } xm = mxCreateDoubleMatrix(8, 1, mxREAL); mxSetField(plhs[0], 0, "w", xm); dest = mxGetPr(xm); src = vars.w; for (i = 0; i < 8; i++) { *dest++ = *src++; } }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Check for proper number of arguments. */ if (nrhs!=9 and nrhs!=11) { mexErrMsgTxt("9 or 11 inputs required."); } const int dim=(nrhs-4)/2; //mexPrintf("Dimension of images: %i\n",dim); const mxClassID classID = mxGetClassID(prhs[0]); /* The first inputs must be noncomplex double matrices.*/ for (int n=0; n<2*dim+2; n++) { if ( mxGetClassID(prhs[n])!=classID || mxIsComplex(prhs[n]) ) { mexErrMsgTxt("Input must be a noncomplex floating point."); } if ( mxGetNumberOfDimensions(prhs[n]) != dim ) { mexErrMsgTxt("The dimension of the inputs must agree with the number of inputs."); } for (int dd=0; dd<dim; dd++) { if ( mxGetDimensions(prhs[n])[dd] != mxGetDimensions(prhs[0])[dd] ) { mexErrMsgTxt("Inputs must have the same size."); } } } /* Check last input */ for (int n=2*dim+4; n<2*dim+5; n++) { if ( !mxIsDouble(prhs[n]) || mxIsComplex(prhs[n]) ) { mexErrMsgTxt("Last input must be double."); } if ( mxGetM(prhs[n]) != 1 || mxGetN(prhs[n]) != 1 ) { mexErrMsgTxt("The dimension of the last input must be one."); } } if (static_cast<unsigned int>( mxGetPr(prhs[2*dim+4])[0] ) > 0) { int ii = 2*dim + 2; if ( mxGetClassID(prhs[ii])!=classID || mxIsComplex(prhs[ii]) ) { mexErrMsgTxt("Input must be a noncomplex floating point."); } if ( mxGetNumberOfDimensions(prhs[ii]) != dim ) { mexErrMsgTxt("The dimension of the inputs must agree with the number of inputs."); } for (int dd=0; dd<dim; dd++) { if ( mxGetDimensions(prhs[ii])[dd] != mxGetDimensions(prhs[0])[dd] ) { mexErrMsgTxt("Inputs must have the same size."); } } } if (static_cast<unsigned int>( mxGetPr(prhs[2*dim+4])[0] ) > 0) { int ii = 2*dim + 3; if ( mxGetClassID(prhs[ii])!=classID || mxIsComplex(prhs[ii]) ) { mexErrMsgTxt("Input must be a noncomplex floating point."); } if ( mxGetNumberOfDimensions(prhs[ii]) != dim ) { mexErrMsgTxt("The dimension of the inputs must agree with the number of inputs."); } for (int dd=0; dd<dim; dd++) { if ( mxGetDimensions(prhs[ii])[dd] != mxGetDimensions(prhs[0])[dd] ) { mexErrMsgTxt("Inputs must have the same size."); } } } if (nlhs != dim) { mexErrMsgTxt("Number of outputs must agree with the number of inputs."); } switch ( dim ) { case 2: switch ( classID ) { case mxSINGLE_CLASS: invcondemonsforces<float,2>(nlhs, plhs, nrhs, prhs); break; case mxDOUBLE_CLASS: invcondemonsforces<double,2>(nlhs, plhs, nrhs, prhs); break; default: mexErrMsgTxt("Pixel type unsupported."); } break; case 3: switch ( classID ) { case mxSINGLE_CLASS: invcondemonsforces<float,3>(nlhs, plhs, nrhs, prhs); break; case mxDOUBLE_CLASS: invcondemonsforces<double,3>(nlhs, plhs, nrhs, prhs); break; default: mexErrMsgTxt("Pixel type unsupported."); } break; default: mexErrMsgTxt("Dimension unsupported."); } return; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *xd; /* input data, size Nd*n */ double *xs; /* SVM data, size Ns*n */ double *y; /* output data, size Nd*1 */ double *a; /* SVM coefficients, size Ns*1 */ double b; /* bias term, scalar */ long Nd; /* number of input data */ long Ns; /* number of SVM data */ long n; /* dimension of input space */ long d; /* number of output dimensions */ int *dy; /* dimensions of output vector*/ long i,j; /* counters */ kernel ker; /* kernel function */ mxArray *F; /* field of MATLAB struct */ if (nrhs!=2) mexErrMsgTxt("Invalid number of input arguments."); if (nlhs>2) mexErrMsgTxt("Invalid number of output arguments."); /* --- check input arguments --- */ if ( mxGetNumberOfElements(prhs[0]) != 1 || !mxIsStruct(prhs[0]) || getSvm(prhs[0],&a,&xs,&Ns,&n,&b,&ker) ) mexErrMsgTxt("Invalid first argument (support vector machine)."); if ( mxIsEmpty(prhs[1]) || !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) ) mexErrMsgTxt("Invalid second argument (input data)."); if (nlhs > 1) { if ( (F=mxGetField(prhs[0],0,FNAME_PROB)) == NULL || mxIsEmpty(F) || mxGetNumberOfDimensions(F) > 2 || !mxIsDouble(F) || mxIsComplex(F) || mxGetNumberOfElements(F) != 2 ) mexErrMsgTxt("SVM does not contain valid probability information."); } /* --- get input arguments --- */ d = mxGetNumberOfDimensions(prhs[1]); /* get true number of input dims */ dy = (int*)mxGetDimensions(prhs[1]); while ( d>2 && dy[d-1]==1 ) d--; if ( dy[d-1]==n ) /* compute number of output dims */ d--; else if ( n>1 ) mexErrMsgTxt("Sizes of SVM and input data do not match."); xd = mxGetPr(prhs[1]); /* get input data */ Nd = 1; for (i=0; i<d; i++) Nd *= dy[i]; /* --- compute SVM output --- */ plhs[0] = mxCreateNumericArray(d,dy,mxDOUBLE_CLASS,mxREAL); y = mxGetPr(plhs[0]); for (i=0; i<Nd; i++) { y[i] = b; for (j=0; j<Ns; j++) y[i] += a[j]*calcKernel(xd+i,Nd,xs+j,Ns,n,&ker); } /* --- compute probabilities --- */ if (nlhs > 1) { double *p; /* probability matrix */ double predict; /* temporary computation value */ double probA = (mxGetPr(mxGetField(prhs[0],0,FNAME_PROB)))[0]; double probB = (mxGetPr(mxGetField(prhs[0],0,FNAME_PROB)))[1]; plhs[1] = mxCreateNumericArray(d,dy,mxDOUBLE_CLASS,mxREAL); p = mxGetPr(plhs[1]); /* probability computation due to svm.cpp */ #define min_prob 1e-7 for (i=0; i<Nd; i++) { predict = y[i]*probA + probB; if (predict<0) predict = 1.0/(1.0+exp(predict)); else predict = 1.0-1.0/(1.0+exp(-predict)); if (y[i]<0) /* always use PREDICTED class */ predict = 1-predict; p[i] = (predict > 1-min_prob) ? 1-min_prob : predict; } } }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { switch( nrhs ) { /* Note: Fall through is intentional */ /* Argument 3: Specifies 1st pivot */ case 3: if( mxIsComplex(prhs[2]) ) mexErrMsgTxt("Third argument must be real."); if( mxGetNumberOfElements(prhs[2]) != 1 ) mexErrMsgTxt("Third argument must be a scalar."); if( mxGetClassID(prhs[2]) != mxGetClassID(prhs[1]) ) mexErrMsgTxt("Third argument must be of same type as second argument."); /* Argument 2: Either weights or first pivot (for median) */ case 2: if( mxIsComplex(prhs[1]) ) mexErrMsgTxt("Seond argument must be real."); if( mxGetClassID(prhs[1]) != mxGetClassID(prhs[0]) ) mexErrMsgTxt("Second argument must be of same type as first argument."); { const mwSize* dim1 = mxGetDimensions(prhs[1]); if( ((dim1[0] != 1) && (dim1[1] != 1)) && (mxGetNumberOfElements(prhs[1]) != 1) ) { mexErrMsgTxt("Second argument must be a vector (weights) or scalar (pivot)."); } } /* Argument 1: Data (N elements) */ case 1: if( mxIsComplex(prhs[0]) ) mexErrMsgTxt("wmedianf does only support real arguments"); { const mwSize* dim0 = mxGetDimensions(prhs[0]); if( (dim0[0] != 1) && (dim0[1] != 1) ) { mexErrMsgTxt("First argument must be a vector"); } } break; default: mexErrMsgTxt("wmedianf needs at least 1 but no more than 3 arguments."); } if( nlhs <= 0 ) mexErrMsgTxt("wmedianf must have at least one return element"); #if _DEBUG // Reset counter of comparisons int num_comparisons = 0; #endif mwSize N = mxGetNumberOfElements(prhs[0]); mwSize NW = 1; // Number weights if( nrhs >= 2 ) NW = mxGetNumberOfElements(prhs[1]); if( (NW != N) && (NW != 1) ) mexErrMsgTxt("Number of weights must either be a scalar or same size as x."); switch( mxGetClassID(prhs[0]) ) { case mxDOUBLE_CLASS: { /* Pointer for the real part of the input */ mxArray* x_mx = mxDuplicateArray(prhs[0]); double* x = (double*)mxGetData(x_mx); double* pivot = 0; // If there are 3 arguments the last on is the pivot if( nrhs >= 3 ) pivot = (double*)mxGetData(prhs[2]); // If there are 2 arguments and the second one is a scalar this is the pivot then. if( (nrhs == 2) && (mxGetNumberOfElements(prhs[1]) == 1) ) pivot = (double*)mxGetData(prhs[1]); plhs[0] = mxCreateNumericMatrix(1, 1, mxDOUBLE_CLASS, mxREAL); double* y = (double*)mxGetData(plhs[0]); if( NW > 1 ) { // Compute weighted median double* w = (double*)mxGetData(mxDuplicateArray(prhs[1])); #if _DEBUG *y = wmedianf(x, w, pivot, (int)N, -1.0, num_comparisons); #else *y = wmedianf(x, w, pivot, (int)N, -1.0); #endif } else { // Compute standard median. #if _DEBUG *y = medianf(x, pivot, (int)N, num_comparisons); #else *y = medianf(x, pivot, (int)N); #endif } #if _DEBUG if( nlhs >= 2 ) { plhs[1] = mxCreateNumericMatrix(1, 1, mxINT32_CLASS, mxREAL); int* c = (int*)mxGetData(plhs[1]); *c = num_comparisons; } #else if( nlhs >= 2 ) { mexErrMsgTxt("This is the release build and hence doesn't calculate number of comparisions."); } #endif break; } case mxSINGLE_CLASS: // TODO case mxUINT32_CLASS: // TODO default: mexErrMsgTxt("Unsuporrted type."); } }
void mexFunction(int nlhs, /* No. of output arguments */ mxArray *plhs[], /* Output arguments. */ int nrhs, /* No. of input arguments. */ const mxArray *prhs[]) /* Input arguments. */ { int ndim = 0, chk_ndim = 0; int n = 0, i = 0; int tm = 0, tn = 0; const int *cdim = NULL, *chk_cdim = NULL; unsigned int dim[3]; double *pm = NULL; double *vm = NULL; double *wm = NULL; double *mask = NULL; double *thres = NULL; double *opm = NULL; double *owm = NULL; double *tpm = NULL; double *twm = NULL; if (nrhs == 0) mexErrMsgTxt("usage: [pm,wm]=pm_ff_unwrap(pn,vm,wm,mask,thres)"); if (nrhs != 5) mexErrMsgTxt("pm_ff_unwrap: 5 input arguments required"); if (nlhs != 2) mexErrMsgTxt("pm_ff_unwrap: 2 output argument required"); /* Get phase map. */ if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0])) { mexErrMsgTxt("pm_ff_unwrap: pm must be numeric, real, full and double"); } ndim = mxGetNumberOfDimensions(prhs[0]); if ((ndim < 2) | (ndim > 3)) { mexErrMsgTxt("pm_ff_unwrap: pm must be 2 or 3-dimensional"); } cdim = mxGetDimensions(prhs[0]); pm = mxGetPr(prhs[0]); /* Get variance-map. */ if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) { mexErrMsgTxt("pm_ff_unwrap: vm must be numeric, real, full and double"); } chk_ndim = mxGetNumberOfDimensions(prhs[1]); if (chk_ndim != ndim) { mexErrMsgTxt("pm_ff_unwrap: pm and vm must have same dimensionality"); } chk_cdim = mxGetDimensions(prhs[1]); for (i=0; i<ndim; i++) { if (cdim[i] != chk_cdim[i]) { mexErrMsgTxt("pm_ff_unwrap: pm and vm must have same size"); } } vm = mxGetPr(prhs[1]); /* Get wrap-map. */ if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2])) { mexErrMsgTxt("pm_ff_unwrap: wm must be numeric, real, full and double"); } chk_ndim = mxGetNumberOfDimensions(prhs[2]); if (chk_ndim != ndim) { mexErrMsgTxt("pm_ff_unwrap: pm and wm must have same dimensionality"); } chk_cdim = mxGetDimensions(prhs[2]); for (i=0; i<ndim; i++) { if (cdim[i] != chk_cdim[i]) { mexErrMsgTxt("pm_ff_unwrap: pm and wm must have same size"); } } wm = mxGetPr(prhs[2]); /* Get mask. */ if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsDouble(prhs[3])) { mexErrMsgTxt("pm_ff_unwrap: mask must be numeric, real, full and double"); } chk_ndim = mxGetNumberOfDimensions(prhs[3]); if (chk_ndim != ndim) { mexErrMsgTxt("pm_ff_unwrap: pm and mask must have same dimensionality"); } chk_cdim = mxGetDimensions(prhs[3]); for (i=0; i<ndim; i++) { if (cdim[i] != chk_cdim[i]) { mexErrMsgTxt("pm_ff_unwrap: pm and mask must have same size"); } } mask = mxGetPr(prhs[3]); /* Fix dimensions to allow for 2D and 3D data. */ dim[0]=cdim[0]; dim[1]=cdim[1]; if (ndim==2) {dim[2]=1; ndim=3;} else {dim[2]=cdim[2];} for (i=0, n=1; i<ndim; i++) { n *= dim[i]; } /* Get scalar or array of thresholds. */ if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4])) { mexErrMsgTxt("pm_ff_unwrap: thres must be numeric, real, full and double"); } tm = mxGetM(prhs[4]); tn = mxGetN(prhs[4]); if (tm>1 && tn>1) { mexErrMsgTxt("pm_ff_unwrap: thres must be scalar or 1D array"); } tn = MAX(tm,tn); thres = mxGetPr(prhs[4]); /* Allocate memory for output. */ plhs[0] = mxCreateNumericArray(ndim,dim,mxDOUBLE_CLASS,mxREAL); opm = mxGetPr(plhs[0]); plhs[1] = mxCreateNumericArray(ndim,dim,mxDOUBLE_CLASS,mxREAL); owm = mxGetPr(plhs[1]); /* Allocate scratch pad. */ tpm = (double *) mxCalloc(n,sizeof(double)); twm = (double *) mxCalloc(n,sizeof(double)); memcpy(tpm,pm,n*sizeof(double)); memcpy(twm,wm,n*sizeof(double)); for (i=0; i<tn; i++) { ff_unwrap(tpm,vm,twm,mask,dim,thres[i],opm,owm); memcpy(tpm,opm,n*sizeof(double)); memcpy(twm,owm,n*sizeof(double)); } mxFree(tpm); mxFree(twm); return; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *SparseMOut; double *SparseMIn; double *SamplePIn; double *SupMask; double *rS,*cS; unsigned int m,n,Supm,Supn,Sm,Sn; /* Check for proper number of arguments */ if (nrhs != 5) { mexErrMsgTxt("Five input arguments required."); } else if (nlhs > 1) { mexErrMsgTxt("Too many output arguments."); } /* Check the dimensions of the inputs. */ m = mxGetM(RowS); n = mxGetN(RowS); if (!mxIsDouble(RowS) || mxIsComplex(RowS) || (MAX(m,n) != 1)) { mexErrMsgTxt("The row size should be a scalar."); } m = mxGetM(ColS); n = mxGetN(ColS); if (!mxIsDouble(ColS) || mxIsComplex(ColS) || (MAX(m,n) != 1)) { mexErrMsgTxt("The column size should be a scalar."); } m = mxGetM(SMATRIX_IN); n = mxGetN(SMATRIX_IN); if (!mxIsDouble(SMATRIX_IN) || mxIsComplex(SMATRIX_IN)) { mexErrMsgTxt("Input Sparse Matrix Format is not right."); } Supm = mxGetM(SUP_MASK); Supn = mxGetN(SUP_MASK); if (!mxIsDouble(SUP_MASK) || mxIsComplex(SUP_MASK) || Supm !=m || Supn != n) { mexErrMsgTxt("Input Superpixel Mask is not right."); } Sm = mxGetM(SAMPLE_P); /*/Number of Rows equals to Number of points to calculate*/ Sn = mxGetN(SAMPLE_P); if (!mxIsDouble(SAMPLE_P) || mxIsComplex(SAMPLE_P) || Sn != 2) { mexErrMsgTxt("Input Sample Point Index format should be Integer matrix of size M by 2."); } /* Create a matrix for the return argument */ SMATRIX_OUT = mxCreateDoubleMatrix(Sm, 1, mxREAL); /* Assign pointers to the various parameters */ SparseMOut = mxGetPr(SMATRIX_OUT); rS = mxGetPr(RowS); cS = mxGetPr(ColS); SparseMIn = mxGetPr(SMATRIX_IN); SamplePIn = mxGetPr(SAMPLE_P); SupMask = mxGetPr(SUP_MASK); /* Do the actual computations in a subroutine */ avgImg(SparseMOut,*rS,*cS,SamplePIn,SupMask,SparseMIn,m,n,Sm); return; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSize i; mwSize dm[4]; float *p = NULL, w[3]; unsigned char *q = NULL; float *G = NULL; int code=0; if (nrhs<3 || nrhs>4 || nlhs>1) mexErrMsgTxt("Incorrect usage"); if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsUint8(prhs[0])) mexErrMsgTxt("First arg must be numeric, real, full and uint8."); if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsSingle(prhs[1])) mexErrMsgTxt("Second arg must be numeric, real, full and single."); if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2])) mexErrMsgTxt("Third arg must be numeric, real and full."); if (mxGetNumberOfDimensions(prhs[0])!= mxGetNumberOfDimensions(prhs[1]) || mxGetNumberOfDimensions(prhs[0])>4) mexErrMsgTxt("First or second args have wrong number of dimensions."); for(i=0; i<mxGetNumberOfDimensions(prhs[0]); i++) dm[i] = mxGetDimensions(prhs[0])[i]; for(i=mxGetNumberOfDimensions(prhs[0]); i<4; i++) dm[i] = 1; if (dm[3]>MAXCLASSES) mexErrMsgTxt("Too many classes."); for(i=0; i<4; i++) if (mxGetDimensions(prhs[1])[i] != dm[i]) mexErrMsgTxt("First and second args have incompatible dimensions."); if (mxGetDimensions(prhs[2])[1] == 1) { code = 2; if (mxGetDimensions(prhs[2])[0] != dm[3]) mexErrMsgTxt("Third arg has incompatible dimensions."); if (!mxIsSingle(prhs[2])) mexErrMsgTxt("Third arg must be single."); } else if (mxGetNumberOfDimensions(prhs[2])==2) { code = 1; if (mxGetDimensions(prhs[2])[0] != dm[3] || mxGetDimensions(prhs[2])[1] != dm[3]) mexErrMsgTxt("Third arg has incompatible dimensions."); if (!mxIsSingle(prhs[2])) mexErrMsgTxt("Third arg must be single."); } else if (mxGetNumberOfDimensions(prhs[2])==5) { code = 3; for(i=0; i<4; i++) if (mxGetDimensions(prhs[2])[i] != dm[i]) mexErrMsgTxt("Third arg has incompatible dimensions."); if (mxGetDimensions(prhs[2])[4] != dm[3]) mexErrMsgTxt("Third arg has incompatible dimensions."); if (!mxIsSingle(prhs[2])) mexErrMsgTxt("Third arg must be single."); } else if (mxGetNumberOfDimensions(prhs[2])==4) { for(i=0; i<3; i++) if (mxGetDimensions(prhs[2])[i] != dm[i]) mexErrMsgTxt("Third arg has incompatible dimensions."); if (mxGetDimensions(prhs[2])[3] != (dm[3]*(dm[3]-1))/2) mexErrMsgTxt("Third arg has incompatible dimensions."); if (mxIsSingle(prhs[2])) code = 4; else if (mxIsUint8(prhs[0])) code = 5; else mexErrMsgTxt("Third arg must be either single or uint8."); } else mexErrMsgTxt("Third arg has incompatible dimensions."); p = (float *)mxGetData(prhs[1]); G = (float *)mxGetData(prhs[2]); if (nrhs>=4) { /* Adjustment for anisotropic voxel sizes. w should contain the square of each voxel size. */ if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsSingle(prhs[3])) mexErrMsgTxt("Fourth arg must be numeric, real, full and single."); if (mxGetNumberOfElements(prhs[3]) != 3) mexErrMsgTxt("Fourth arg must contain three elements."); for(i=0; i<3; i++) w[i] = ((float *)mxGetData(prhs[3]))[i]; } else { for(i=0; i<3; i++) w[i] = 1.0; } if (nlhs>0) { /* Copy input to output */ unsigned char *q0; plhs[0] = mxCreateNumericArray(4,dm, mxUINT8_CLASS, mxREAL); q0 = (unsigned char *)mxGetData(prhs[0]); q = (unsigned char *)mxGetData(plhs[0]); for(i=0; i<dm[0]*dm[1]*dm[2]*dm[3]; i++) q[i] = q0[i]; } else /* Note the nasty side effects - but it does save memory */ q = (unsigned char *)mxGetData(prhs[0]); mrf1(dm, q,p,G,w,code); }
/* * The mex function runs a max-flow min-cut problem. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mbglIndex i,j,k; mbglIndex mrows, ncols; mbglIndex n,nz; /* sparse matrix */ mwIndex *A_row, *A_col; double *A_val; /* source/sink */ mbglIndex u, v; /* algorithm name */ char *algname; /* flow matrix connectivity */ mbglIndex *pi_flow, *j_flow; /* capacity and residual structures */ int *cap, *res; /* reverse edge map */ mbglIndex *rev_edge_map; /* result */ int flow; /* output */ double *pflowval; double *pmincut; double *pri; double *prj; double *prv; /* * The current calling pattern is * matching_mex(A,verify,initial_match_name,augmenting_path_name) */ const mxArray* arg_matrix; const mxArray* arg_source; const mxArray* arg_sink; const mxArray* arg_algname; int required_arguments = 4; if (nrhs != required_arguments) { mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument", "the function requires %i arguments, not %i\n", required_arguments, nrhs); } arg_matrix = prhs[0]; arg_source = prhs[1]; arg_sink = prhs[2]; arg_algname = prhs[3]; u = (mbglIndex)load_scalar_arg(arg_source,1); v = (mbglIndex)load_scalar_arg(arg_sink,2); algname = load_string_arg(arg_algname,3); /* The first input must be a sparse matrix. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if (mrows != ncols || !mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) { mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument", "the matrix must be sparse, square, and double valued"); } n = mrows; /* Get the sparse matrix */ A_val = mxGetPr(prhs[0]); A_row = mxGetIr(prhs[0]); A_col = mxGetJc(prhs[0]); nz = A_col[n]; /* Quick input check */ if (u > n || u < 1) { mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument", "invalid source vertex: %i\n", u); } if (v > n || v < 1) { mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument", "invalid sink vertex: %i\n", v); } u = u-1; v = v-1; /* build flow connectivity structure */ build_matrix(n,A_row,A_col,A_val, &pi_flow, &j_flow, &cap, &rev_edge_map); /* allocate the residual map */ res = mxCalloc(sizeof(int),pi_flow[n]); /*i = 0; for (k=0; k < pi_flow[n]; k++) { // get the correct row while (k >= pi_flow[i+1]) { ++i; } mexPrintf("(%i,%i) (%i,%i)\n", i,j_flow[k],cap[k],res[k]); }*/ /* mexPrintf("Calling flow (%i,%i)...\n", u, v); */ #ifdef _DEBUG mexPrintf("max_flow(%s)...", algname); #endif if (strcmp(algname,"push_relabel") == 0) { push_relabel_max_flow(n,j_flow,pi_flow, u,v,cap,res,rev_edge_map,&flow); } else if (strcmp(algname, "edmunds_karp") == 0) { edmonds_karp_max_flow(n,j_flow,pi_flow, u,v,cap,res,rev_edge_map,&flow); } else if (strcmp(algname, "kolmogorov") == 0) { boykov_kolmogorov_max_flow(n,j_flow,pi_flow, u,v,cap,res,rev_edge_map,&flow); } else { mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument", "algname option %s is invalid\n", algname); } #ifdef _DEBUG mexPrintf("done!\n"); #endif /*i = 0; for (k=0; k < pi_flow[n]; k++) { // get the correct row while (k >= pi_flow[i+1]) { ++i; } mexPrintf("(%i,%i) (%i,%i)\n", i,j_flow[k],cap[k],res[k]); }*/ if (nlhs >= 1) { plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL); pflowval = mxGetPr(plhs[0]); pflowval[0] = (double)flow; } if (nlhs >= 2) { int *pimincut; plhs[1] = mxCreateDoubleMatrix(n,1,mxREAL); pmincut = mxGetPr(plhs[1]); pimincut = (int*)pmincut; build_cut(u, n, pi_flow, j_flow, cap, res, pimincut); test_cut(flow,pimincut,n,A_row,A_col,A_val); /* now expand mincut to the full dataset, we need to * do this operation backwards because pimincut has integer * entries specified and we are expanding them to double. */ expand_int_to_double(pimincut,pmincut,n,0.0); } if (nlhs >= 3) { plhs[2] = mxCreateDoubleMatrix(nz,1,mxREAL); plhs[3] = mxCreateDoubleMatrix(nz,1,mxREAL); plhs[4] = mxCreateDoubleMatrix(nz,1,mxREAL); pri = mxGetPr(plhs[2]); prj = mxGetPr(plhs[3]); prv = mxGetPr(plhs[4]); /* j will be our index into the new matrix. */ j = 0; for (i=0;i<n;i++) { for (k=pi_flow[i];k<pi_flow[i+1];k++) { if (cap[k] != 0) { /* since cap[k] != 0, this is a real edge */ pri[j] = i+1; prj[j] = j_flow[k]+1; prv[j] = res[k]; j++; } } } if (j != nz) { mexPrintf("error... j != nz...\n"); } } #ifdef _DEBUG mexPrintf("return\n"); #endif }
void robustpn(int nout, mxArray* pout[], int nin, const mxArray* pin[]) { /* ********************************************************* * Check inputs and construct the energy ********************************************************** */ int nLabel, nVar, nPair, nHigher, ii; int hop_fields_indices[HOP_N_OF_FIELDS]; // indices to fields in hop struct // check pin[0] is sparse if ( ! mxIsSparse(pin[0]) || ! mxIsDouble(pin[0]) || mxIsComplex(pin[0])) mexErrMsgIdAndTxt("robustpn:inputs","sparseG must be a sparse double matrix"); // check pin[0] is square const mwSize *spd = mxGetDimensions(pin[0]); if (spd[0] != spd[1]) mexErrMsgIdAndTxt("robustpn:inputs","sparseG must be a square matrix"); nVar = spd[0]; nPair = 0; // read the sparse matrix double* Pr = mxGetPr(pin[0]); mwIndex *ir = mxGetIr(pin[0]); mwIndex *jc = mxGetJc(pin[0]); mwIndex col, starting_row_index, stopping_row_index, current_row_index, tot(0); mwSize max_npair = mxGetNzmax(pin[0]); int * pairs = new int[2 * max_npair]; // will be de-alocate on ~Energy termType* sc = new termType[max_npair]; // will be de-alocate on ~Energy // mexPrintf("Preparing to read sG\n"); // traverse the sparseG matrix - pick only connections from the upper tri of the matrix // (since its symmetric and we don't want to count each potential twice). for (col=0; col<nVar; col++) { starting_row_index = jc[col]; stopping_row_index = jc[col+1]; if (starting_row_index == stopping_row_index) continue; else { for (current_row_index = starting_row_index; current_row_index < stopping_row_index ; current_row_index++) { if ( ir[current_row_index] >= col ) { // ignore lower tri of matrix pairs[nPair*2] = ir[current_row_index]; // from pairs[nPair*2 + 1] = col; // to sc[nPair] = (termType)Pr[tot]; // potential weight nPair++; } tot++; } } } // mexPrintf("Done reading sG got %d pairs\n", nPair); // check pin[1] has enough columns (=#nodes) const mwSize *sdc = mxGetDimensions(pin[1]); if (sdc[1] != spd[0]) mexErrMsgIdAndTxt("robustpn:inputs","Dc must have %d columns to match graph structure", spd[0]); nLabel = sdc[0]; // check pin[2] is struct array with proper feilds if ( mxGetClassID(pin[2]) != mxSTRUCT_CLASS ) mexErrMsgIdAndTxt("robustpn:inputs","hop must be a struct array"); nHigher = mxGetNumberOfElements(pin[2]); // expecting HOP_N_OF_FIELDS fieds if ( mxGetNumberOfFields(pin[2]) != HOP_N_OF_FIELDS ) mexErrMsgIdAndTxt("robustpn:inputs","hop must have %d fields", HOP_N_OF_FIELDS); // chack that we have the right fields for ( ii = 0; ii < HOP_N_OF_FIELDS ; ii++ ) { hop_fields_indices[ii] = mxGetFieldNumber(pin[2], HOP_FIELDS[ii]); if ( hop_fields_indices[ii] < 0 ) mexErrMsgIdAndTxt("robustpn:inputs","hop is missing %s field", HOP_FIELDS[ii]); } Energy<termType> *energy = new Energy<termType>(nLabel, nVar, nPair, nHigher); energy->SetUnaryCost( (termType*)mxGetData(pin[1]) ); energy->SetPairCost(pairs, sc); delete[] pairs; // were copied into energy delete[] sc; // Add the HO potentials mxArray *xind, *xw, *xgamma, *xQ; int * ind, n; termType* w; termType* gamma; termType Q; for ( ii = 0 ; ii < nHigher; ii++ ) { xind = mxGetFieldByNumber(pin[2], ii, hop_fields_indices[0]); n = mxGetNumberOfElements(xind); ind = new int[n]; // allocation for energy GetArr(xind, ind, -1); // bias = -1 convert from 1-ind of matlab to 0-ind of C xw = mxGetFieldByNumber(pin[2], ii, hop_fields_indices[1]); if ( mxGetNumberOfElements(xw) != n ) { delete energy; delete[] ind; mexErrMsgIdAndTxt("robustpn:inputs","hop %d: number of indices is different than number of weights", ii); } w = new termType[n]; // allocation for energy GetArr(xw, w); xgamma = mxGetFieldByNumber(pin[2], ii, hop_fields_indices[2]); if ( mxGetNumberOfElements(xgamma) != nLabel+1 ) { delete energy; delete[] ind; delete[] w; mexErrMsgIdAndTxt("robustpn:inputs","hop %d: must have exactly %d gamma values", ii, nLabel+1); } gamma = new termType[nLabel+1]; GetArr(xgamma, gamma); xQ = mxGetFieldByNumber(pin[2], ii, hop_fields_indices[3]); Q = (termType)mxGetScalar(xQ); if ( energy->SetOneHOP(n, ind, w, gamma, Q) < 0 ) { delete energy; delete[] gamma; mexErrMsgIdAndTxt("robustpn:inputs","failed to load hop #%d", ii); } delete[] gamma; // this array is being allocated inside energy // mexPrintf("Done reading hop(%d) / %d\n", ii, nHigher); } // mexPrintf("Done reading hops\n"); /* ********************************************************* * Minimize energy ********************************************************** */ //initialize alpha expansion - max MAX_ITER iterations AExpand<termType> *expand = new AExpand<termType>(energy, MAX_ITER); // must have at least one output for the labels pout[0] = mxCreateNumericMatrix(1, nVar, mxINT32_CLASS, mxREAL); int *solution = (int*)mxGetData(pout[0]); // Do we have an initial guess of labeling ? if ( nin == 4 ) { if ( mxGetNumberOfElements(pin[3]) != nVar ) mexErrMsgIdAndTxt("robustpn:inputs","Initial guess of labeling must have exactly %d elements", nVar); GetArr(pin[3], solution, -1); // convert Matlab's 1-ind labeling to C's 0-ind labeling } else { // default initial labeling memset(solution, 0, nVar*sizeof(int)); } termType ee[3]; termType E(0); E = expand->minimize(solution, ee); if (nout>1) { pout[1] = mxCreateNumericMatrix(1, 4, mxGetClassID(pin[1]), mxREAL); termType *pE = (termType*)mxGetData(pout[1]); pE[0] = ee[0]; pE[1] = ee[1]; pE[2] = ee[2]; pE[3] = E; } // de-allocate delete expand; delete energy; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* matlab usage: pdos(data,cone,params); */ Data *d; Cone *k; const Sol *sol; const mxArray *data; const mxArray *A_mex; const mxArray *b_mex; const mxArray *c_mex; const mxArray *f_mex; const mxArray *l_mex; const mxArray *q_mex; const double *q_mex_vals; const mxArray *x0; const mxArray *y0; const mxArray *s0; const mxArray *cone; const mxArray *params; idxint i; if (nrhs != 3){ mexErrMsgTxt("Three arguments are required in this order: data struct, cone struct, params struct"); } if (nlhs > 4) { mexErrMsgTxt("PDOS has up to 4 output arguments only."); } d = mxMalloc(sizeof(Data)); k = mxMalloc(sizeof(Cone)); d->p = mxMalloc(sizeof(Params)); data = prhs[0]; cone = prhs[1]; params = prhs[2]; A_mex = (mxArray *) mxGetField(data,0,"A"); if(A_mex == NULL) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Data struct must contain a `A` entry."); } if (!mxIsSparse(A_mex)){ mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Input matrix A must be in sparse format (pass in sparse(A))"); } if (mxIsComplex(A_mex)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Input matrix A cannot be complex"); } b_mex = (mxArray *) mxGetField(data,0,"b"); if(b_mex == NULL) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Data struct must contain a `b` entry."); } if(mxIsSparse(b_mex)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Input vector b must be dense (pass in full(b))"); } if (mxIsComplex(b_mex)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Input vector b cannot be complex"); } c_mex = (mxArray *) mxGetField(data,0,"c"); if(c_mex == NULL) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Data struct must contain a `c` entry."); } if(mxIsSparse(c_mex)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Input vector c must be dense (pass in full(c))"); } if (mxIsComplex(c_mex)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Input vector c cannot be complex"); } x0 = (mxArray *) mxGetField(data,0,"x0"); if(x0 != NULL && mxIsSparse(x0)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Initial vector x0 must be dense (pass in full(x0))"); } if (x0 != NULL && mxIsComplex(x0)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Initial vector x0 cannot be complex"); } y0 = (mxArray *) mxGetField(data,0,"y0"); if(y0 != NULL && mxIsSparse(y0)) { mxFree(d->p); mxFree(d); mxFree(k); mexErrMsgTxt("Initial vector y0 must be dense (pass in full(y0))"); } if (y0 != NULL && mxIsComplex(y0)) { mxFree(d); mxFree(k); mexErrMsgTxt("Initial vector y0 cannot be complex"); } s0 = (mxArray *) mxGetField(data,0,"s0"); if(s0 != NULL && mxIsSparse(s0)) { mxFree(d); mxFree(k); mexErrMsgTxt("Initial vector s0 must be dense (pass in full(s0))"); } if (s0 != NULL && mxIsComplex(s0)) { mxFree(d); mxFree(k); mexErrMsgTxt("Initial vector s0 cannot be complex"); } d->n = getVectorLength(c_mex,"data.c"); d->m = getVectorLength(b_mex,"data.b"); d->b = mxGetPr(b_mex); d->c = mxGetPr(c_mex); d->x = x0 ? mxGetPr(x0) : NULL; d->y = y0 ? mxGetPr(y0) : NULL; d->s = s0 ? mxGetPr(s0) : NULL; d->p->ALPHA = getParameterField(params, "ALPHA", d, k); d->p->MAX_ITERS = (idxint)getParameterField(params, "MAX_ITERS", d, k); d->p->EPS_ABS = getParameterField(params, "EPS_ABS", d, k); d->p->CG_MAX_ITS = (idxint)getParameterField(params, "CG_MAX_ITS", d, k); d->p->CG_TOL = getParameterField(params, "CG_TOL", d, k); d->p->VERBOSE = (idxint)getParameterField(params, "VERBOSE", d, k); d->p->NORMALIZE = (idxint)getParameterField(params, "NORMALIZE", d, k); f_mex = (mxArray *) mxGetField(cone,0,"f"); if(f_mex == NULL) { mxFree(d); mxFree(k); mexErrMsgTxt("Cone struct must contain a `f` entry."); } k->f = (idxint)*mxGetPr(f_mex); l_mex = (mxArray *) mxGetField(cone,0,"l"); if(l_mex == NULL) { mxFree(d); mxFree(k); mexErrMsgTxt("Cone struct must contain a `l` entry."); } k->l = (idxint)*mxGetPr(l_mex); q_mex = (mxArray *) mxGetField(cone,0,"q"); if(q_mex == NULL) { mxFree(d); mxFree(k); mexErrMsgTxt("Cone struct must contain a `q` entry."); } q_mex_vals = mxGetPr(q_mex); k->qsize = getVectorLength(mxGetField(cone,0,"q"), "cone.q"); k->q = mxMalloc(sizeof(idxint)*k->qsize); for ( i=0; i < k->qsize; i++ ){ k->q[i] = (idxint)q_mex_vals[i]; } /* int Anz = mxGetNzmax(A_mex); */ d->Ax = (double *)mxGetPr(A_mex); d->Ai = (long*)mxGetIr(A_mex); d->Ap = (long*)mxGetJc(A_mex); /* printConeData(d,k); */ /* printData(d); */ sol = pdos(d,k); plhs[0] = mxCreateDoubleMatrix(d->n, 1, mxREAL); mxSetPr(plhs[0], sol->x); plhs[1] = mxCreateDoubleMatrix(d->m, 1, mxREAL); mxSetPr(plhs[1], sol->s); plhs[2] = mxCreateDoubleMatrix(d->m, 1, mxREAL); mxSetPr(plhs[2], sol->y); plhs[3] = mxCreateString(sol->status); mxFree(d->p); mxFree(d); mxFree(k->q); mxFree(k); return; }
/* the gateway function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *s,*t; int w; int ns,nt,k; double *dp; /* check for proper number of arguments */ if(nrhs!=2&&nrhs!=3) { mexErrMsgIdAndTxt( "MATLAB:dtw_c:invalidNumInputs", "Two or three inputs required."); } if(nlhs>1) { mexErrMsgIdAndTxt( "MATLAB:dtw_c:invalidNumOutputs", "dtw_c: One output required."); } /* check to make sure w is a scalar */ if(nrhs==2) { w=-1; } else if(nrhs==3) { if( !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || mxGetN(prhs[2])*mxGetM(prhs[2])!=1 ) { mexErrMsgIdAndTxt( "MATLAB:dtw_c:wNotScalar", "dtw_c: Input w must be a scalar."); } /* get the scalar input w */ w = (int) mxGetScalar(prhs[2]); } /* create a pointer to the input matrix s */ s = mxGetPr(prhs[0]); /* create a pointer to the input matrix t */ t = mxGetPr(prhs[1]); /* get the dimensions of the matrix input s */ ns = mxGetM(prhs[0]); k = mxGetN(prhs[0]); /* get the dimensions of the matrix input t */ nt = mxGetM(prhs[1]); if(mxGetN(prhs[1])!=k) { mexErrMsgIdAndTxt( "MATLAB:dtw_c:dimNotMatch", "dtw_c: Dimensions of input s and t must match."); } /* set the output pointer to the output matrix */ plhs[0] = mxCreateDoubleMatrix( 1, 1, mxREAL); /* create a C pointer to a copy of the output matrix */ dp = mxGetPr(plhs[0]); /* call the C subroutine */ dp[0]=dtw_c(s,t,w,ns,nt,k); return; }
/* * The gateway function * [A, M] = MINE_MEX(X, Y, ALPHA, C, EST) * A = [MIC, MAS, MEV, MCN, MCN_GENERAL, TIC] * M (optional) = characteristic matrix (square dense matrix) */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *x, *y; double alpha; int c, est; mwSize ncolsx, ncolsy; mine_problem problem; mine_parameter param; mine_score *score; char *ret; double *out; /* check for proper number of outputs */ if(nlhs > 2) mexErrMsgTxt("Too many output arguments."); /* check for proper number of arguments */ if(nrhs != 5) mexErrMsgTxt("Incorrect number of inputs."); /* check that number of rows in first input argument (x) is 1 */ if(mxGetM(prhs[0]) != 1) mexErrMsgTxt("X must be a row vector."); /* check that number of rows in second input argument (y) is 1 */ if(mxGetM(prhs[1]) != 1) mexErrMsgTxt("Y must be a row vector."); /* make sure the thirth input argument (alpha) is scalar */ if(!mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || mxGetNumberOfElements(prhs[2]) != 1) mexErrMsgTxt("alpha must be a scalar."); /* make sure the fourth input argument (c) is scalar */ if(!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) || mxGetNumberOfElements(prhs[3]) != 1) mexErrMsgTxt("c must be a scalar."); /* make sure the fifth input argument (est) is scalar */ if(!mxIsDouble(prhs[4]) || mxIsComplex(prhs[4]) || mxGetNumberOfElements(prhs[4]) != 1) mexErrMsgTxt("est must be a scalar."); /* get alpha, c and est */ alpha = mxGetScalar(prhs[2]); c = mxGetScalar(prhs[3]); est = (int) mxGetScalar(prhs[4]); /* create a pointers for X and Y */ x = mxGetPr(prhs[0]); y = mxGetPr(prhs[1]); ncolsx = mxGetN(prhs[0]); ncolsy = mxGetN(prhs[1]); /* check the number of elements of X and Y */ if (ncolsx != ncolsy) mexErrMsgTxt("X and Y must have the same number of elements."); /* build param */ param.alpha = alpha; param.c = c; param.est = est; /* check param */ ret = mine_check_parameter(¶m); if(ret) mexErrMsgTxt(ret); /* build problem */ problem.n = (int) ncolsx; problem.x = x; problem.y = y; /* compute the mutual information score */ score = mine_compute_score(&problem, ¶m); if(score == NULL) mexErrMsgTxt("Problem with mine_compute_score()."); /* build the output array*/ plhs[0] = mxCreateDoubleMatrix(1, 6, mxREAL); out = mxGetPr(plhs[0]); out[0] = mine_mic(score); out[1] = mine_mas(score); out[2] = mine_mev(score); out[3] = mine_mcn(score, 0); out[4] = mine_mcn_general(score); out[5] = mine_tic(score); /* return full characteristic matrix */ if (nlhs>1) { mwSize i, j, nrows, ncols; nrows = score->n; ncols = score->m[0]; plhs[1] = mxCreateDoubleMatrix(nrows, ncols, mxREAL); out = mxGetPr(plhs[1]); for (i=0; i<nrows; i++) { for (j=0; j<score->m[i]; j++) out[nrows*j + i] = score->M[i][j]; } } mine_free_score(&score); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int mrows,ncols; mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows==1 && ncols==1) ) { mexErrMsgTxt("Input must be a noncomplex scalar double."); } double * ptmax=mxGetPr(prhs[0]); double * pgamma=mxGetPr(prhs[1]); int marows = mxGetM(prhs[2]); int nacols = mxGetN(prhs[2]); if (nacols!=1) mexErrMsgTxt("a must be a one column vector"); int nap=marows; int mtarows = mxGetM(prhs[3]); int ntacols = mxGetN(prhs[3]); if (ntacols!=1) mexErrMsgTxt("ta must be a one column vector"); if (mtarows != marows) mexErrMsgTxt("ta and k must be have the same length"); int mbrows = mxGetM(prhs[4]); int nbcols = mxGetN(prhs[4]); if (nbcols!=1) mexErrMsgTxt("b must be a one column vector"); int nbp=mbrows; int mtbrows = mxGetM(prhs[5]); int ntbcols = mxGetN(prhs[5]); if (ntbcols!=1) mexErrMsgTxt("tb must be a one column vector"); if (mtbrows != mbrows) mexErrMsgTxt("tb and b must be have the same length"); gsl_error_handler_t * err=gsl_set_error_handler_off (); double samplerate=44100.; double tmax=ptmax[0];/*0.200;*/ double gamma=pgamma[0]; double * alpha=mxGetPr(prhs[2]); double * talpha=mxGetPr(prhs[3]); double * beta=mxGetPr(prhs[4]); double * tbeta=mxGetPr(prhs[5]); double dt=1/(samplerate); int totalframe=ceil(tmax/dt); ODEparams * pa=init(nap,alpha,talpha,nbp,beta,tbeta,gamma,0,1); plhs[0] = mxCreateDoubleMatrix(1,totalframe, mxREAL); double * data = mxGetPr(plhs[0]); runOde(data,tmax,dt,pa); }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int i, j; double *c=NULL, *b=NULL, *A=NULL, *l=NULL, *u=NULL, *x=NULL, *lambda=NULL ; int *iA=NULL, *kA=NULL, *nzA=NULL, neq=0, m=0, n=0, display=0; long *lpenv=NULL, *p_lp=NULL; char *Sense=NULL ; #ifndef MX_COMPAT_32 long *iA_=NULL, *kA_=NULL ; #endif if (nrhs > 8 || nrhs < 1) { mexErrMsgTxt("Usage: [p_lp,how] " "= lp_gen(lpenv,c,A,b,l,u,neq,disp)"); return; } switch (nrhs) { case 8: if (mxGetM(prhs[7]) != 0 || mxGetN(prhs[7]) != 0) { if (!mxIsNumeric(prhs[7]) || mxIsComplex(prhs[7]) || mxIsSparse(prhs[7]) || !(mxGetM(prhs[7])==1 && mxGetN(prhs[7])==1)) { mexErrMsgTxt("8th argument (display) must be " "an integer scalar."); return; } display = *mxGetPr(prhs[7]); } case 7: if (mxGetM(prhs[6]) != 0 || mxGetN(prhs[6]) != 0) { if (!mxIsNumeric(prhs[6]) || mxIsComplex(prhs[6]) || mxIsSparse(prhs[6]) || !(mxGetM(prhs[6])==1 && mxGetN(prhs[6])==1)) { mexErrMsgTxt("7th argument (neq) must be " "an integer scalar."); return; } neq = *mxGetPr(prhs[6]); } case 6: if (mxGetM(prhs[5]) != 0 || mxGetN(prhs[5]) != 0) { if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5]) || mxIsSparse(prhs[5]) || !mxIsDouble(prhs[5]) || mxGetN(prhs[5])!=1 ) { mexErrMsgTxt("6th argument (u) must be " "a column vector."); return; } u = mxGetPr(prhs[5]); n = mxGetM(prhs[5]); } case 5: if (mxGetM(prhs[4]) != 0 || mxGetN(prhs[4]) != 0) { if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4]) || mxGetN(prhs[4])!=1 ) { mexErrMsgTxt("5th argument (l) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[4])) { mexErrMsgTxt("Dimension error (arg 5 and later)."); return; } l = mxGetPr(prhs[4]); n = mxGetM(prhs[4]); } case 4: if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) { if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsDouble(prhs[3]) || mxGetN(prhs[3])!=1 ) { mexErrMsgTxt("4rd argument (b) must be " "a column vector."); return; } if (m != 0 && m != mxGetM(prhs[3])) { mexErrMsgTxt("Dimension error (arg 4 and later)."); return; } b = mxGetPr(prhs[3]); m = mxGetM(prhs[3]); } case 3: if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) { if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || !mxIsSparse(prhs[2]) ) { mexErrMsgTxt("3n argument (A) must be " "a sparse matrix."); return; } if (m != 0 && m != mxGetM(prhs[2])) { mexErrMsgTxt("Dimension error (arg 3 and later)."); return; } if (n != 0 && n != mxGetN(prhs[2])) { mexErrMsgTxt("Dimension error (arg 3 and later)."); return; } m = mxGetM(prhs[2]); n = mxGetN(prhs[2]); A = mxGetPr(prhs[2]); #ifdef MX_COMPAT_32 iA = mxGetIr(prhs[2]); kA = mxGetJc(prhs[2]); #else iA_ = mxGetIr(prhs[2]); kA_ = mxGetJc(prhs[2]); iA = myMalloc(mxGetNzmax(prhs[2])*sizeof(int)) ; for (i=0; i<mxGetNzmax(prhs[2]); i++) iA[i]=iA_[i] ; kA = myMalloc((n+1)*sizeof(int)) ; for (i=0; i<n+1; i++) kA[i]=kA_[i] ; #endif nzA=myMalloc(n*sizeof(int)) ; for (i=0; i<n; i++) nzA[i]=kA[i+1]-kA[i] ; Sense=myMalloc((m+1)*sizeof(char)) ; for (i=0; i<m; i++) if (i<neq) Sense[i]='E' ; else Sense[i]='L' ; Sense[m]=0 ; } case 2: if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) { if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) || mxGetN(prhs[1])!=1 ) { mexErrMsgTxt("2st argument (c) must be " "a column vector."); return; } if (n != 0 && n != mxGetM(prhs[1])) { mexErrMsgTxt("Dimension error (arg 2 and later)."); return; } c = mxGetPr(prhs[1]); n = mxGetM(prhs[1]); } case 1: if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) { if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || mxGetN(prhs[0])!=1 ) { mexErrMsgTxt("1st argument (lpenv) must be " "a column vector."); return; } if (1 != mxGetM(prhs[0])) { mexErrMsgTxt("Dimension error (arg 1)."); return; } lpenv = (long*) mxGetPr(prhs[0]); } } if (nlhs > 2 || nlhs < 1) { mexErrMsgTxt("Usage: [p_lp,how] " "= lp_gen(lpenv,c,A,b,l,u,neq,disp)"); return; } if (display>3) fprintf(STD_OUT, "(m=%i, n=%i, neq=%i) \n", m, n, neq) ; switch (nlhs) { case 2: case 1: plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); p_lp = (long*) mxGetPr(plhs[0]); } if (display>2) fprintf(STD_OUT, "argument processing finished\n") ; { CPXENVptr env = NULL; CPXLPptr lp = NULL; int status, lpstat; double objval; /* Initialize the CPLEX environment */ env = (CPXENVptr) lpenv[0] ; /* Create the problem */ if (display>2) fprintf(STD_OUT, "calling CPXcreateprob \n") ; lp = CPXcreateprob (env, &status, "xxx"); if ( lp == NULL ) { fprintf (STD_OUT,"Failed to create subproblem\n"); status = 1; goto TERMINATE; } if (p_lp) *p_lp=(long) lp ; if (display>2) fprintf(STD_OUT, "calling CPXcopylp (m=%i, n=%i) \n", m, n) ; status = CPXcopylp(env, lp, n, m, CPX_MIN, c, b, Sense, kA, nzA, iA, A, l, u, NULL); if ( status ) { fprintf (STD_OUT, "CPXcopylp failed.\n"); goto TERMINATE; } TERMINATE: if (status) { char errmsg[1024]; CPXgeterrorstring (env, status, errmsg); fprintf (STD_OUT, "%s", errmsg); if (nlhs >= 2) plhs[1] = mxCreateString(errmsg) ; } else if (nlhs >= 2) plhs[1] = mxCreateString("OK") ; ; if (nzA) myFree(nzA) ; #ifndef MX_COMPAT_32 if (iA) myFree(iA) ; if (kA) myFree(kA) ; #endif /*if (Sense) myFree(Sense) ;*/ if (!p_lp) { if ( lp != NULL ) { if (display>2) fprintf(STD_OUT, "calling CPXfreeprob\n") ; status = CPXfreeprob (env, &lp); if ( status ) { fprintf (STD_OUT, "CPXfreeprob failed, error code %d.\n", status); } } } return ; } }
/* * The mex function runs a shortest path problem. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwIndex mrows, ncols; mwIndex n,nz; /* sparse matrix */ mwIndex *ia, *ja; double *a; /* true if this function is reweighted */ int reweighted = 0; double dinf; /* output data */ double *D; int rval; /* sp type string */ int buflen; char *algname; int status; /* * The current calling pattern is * matlab_bgl_all_sp_mex(A,algname,dinf,reweight) * algname is a string with either 'johnson', 'floyd_warshall' * reweight is either a string or a length nnz vector * * if reweight is a length nnz vector, then we use that as the values * for the matrix, if its a string, then we use the values from the * the matrix. */ const mxArray* arg_matrix; const mxArray* arg_algname; const mxArray* arg_dinf; const mxArray* arg_reweight; if (nrhs != 4) { mexErrMsgTxt("4 inputs required."); } arg_matrix = prhs[0]; arg_algname = prhs[1]; arg_dinf = prhs[2]; arg_reweight = prhs[3]; /* First test if they are going to reweight or not */ if (!mxIsChar(arg_reweight)) { reweighted = 1; } /* The first input must be a sparse matrix. */ mrows = mxGetM(arg_matrix); ncols = mxGetN(arg_matrix); if (!reweighted && (mrows != ncols || !mxIsSparse(arg_matrix) || !mxIsDouble(arg_matrix) || mxIsComplex(arg_matrix))) { mexErrMsgTxt("A non-reweighted input matrix must be a noncomplex square sparse matrix."); } else if (reweighted && (mrows != ncols || !mxIsSparse(arg_matrix))) { mexErrMsgTxt("A reweighted input matrix must be a square sparse matrix."); } n = mrows; /* Get the sparse matrix */ /* recall that we've transposed the matrix */ ja = mxGetIr(arg_matrix); ia = mxGetJc(arg_matrix); nz = ia[n]; if (!reweighted) { a = mxGetPr(arg_matrix); } else { /* check the reweighting array to make sure it is acceptable */ if (mxGetNumberOfElements(arg_reweight) < nz) mexErrMsgTxt("The reweight array must have length at least nnz(A)"); if (!mxIsDouble(arg_reweight)) mexErrMsgTxt("The reweight array must be of type double."); a = mxGetPr(arg_reweight); } /* Get the uninitialized value */ dinf = mxGetScalar(arg_dinf); /* Get the algorithm type */ if (mxIsChar(arg_algname) != 1) mexErrMsgTxt("Input 2 must be a string (algname)."); /* Input must be a row vector. */ if (mxGetM(arg_algname) != 1) mexErrMsgTxt("Input 2 must be a row vector."); /* Get the length of the input string. */ buflen = (mxGetM(arg_algname) * mxGetN(arg_algname)) + 1; /* Allocate memory for input and output strings. */ algname = mxCalloc(buflen, sizeof(char)); status = mxGetString(arg_algname, algname, buflen); if (status != 0) mexErrMsgTxt("Not enough space for algname input."); plhs[0] = mxCreateDoubleMatrix(n,n,mxREAL); /* create the output vectors */ D = mxGetPr(plhs[0]); #ifdef _DEBUG mexPrintf("all_sp_%s...",algname); #endif if (strcmp(algname, "johnson") == 0) { rval = johnson_all_sp(n, ja, ia, a, D, dinf); } else if (strcmp(algname, "floyd_warshall") == 0) { double *pred = NULL; if (nlhs > 1) { plhs[1] = mxCreateDoubleMatrix(n,n,mxREAL); pred = mxGetPr(plhs[1]); } rval = floyd_warshall_all_sp(n, ja, ia, a, D, dinf, (mbglIndex*)pred); if (pred) { mwIndex i; expand_index_to_double((mwIndex*)pred, pred, n*n, 1.0); /* zero out entries on the diagonal */ for (i=0; i<n; i++) { pred[i+i*n]=0.0; } } } else { mexErrMsgTxt("Unknown algname."); return; } #ifdef _DEBUG mexPrintf("done!\n"); #endif if (rval != 0) { mexErrMsgTxt("Negative weight cycle detected, check the input."); } #ifdef _DEBUG mexPrintf("return\n"); #endif }
void mexFunction(const int nlhs, mxArray *plhs[], const int nrhs, const mxArray *prhs[]) { size_t n,j; size_t nCard; bool isLast, lastPassed; mxArray *codeArray; if(nrhs<1){ mexErrMsgTxt("Not enough inputs."); } if(nrhs>2){ mexErrMsgTxt("Too many inputs."); } if(nlhs>4) { mexErrMsgTxt("Too many outputs."); } //If an empty code matrix is passed, then the second argument is //required, and we will return the first gray code in the sequence. if(mxIsEmpty(prhs[0])) { mwSize dims[2]; if(nrhs<2) { mexErrMsgTxt("The second argument is required when an empty code matrix is passed."); } dims[0]=getSizeTFromMatlab(prhs[1]); dims[1]=1; //Allocate the array; this also initializes all of the elements to //0. codeArray=mxCreateLogicalArray(2, dims); //This is the code plhs[0]=codeArray; if(nlhs>1) { //This is nCard plhs[1]=mxCreateDoubleScalar(0.0); if(nlhs>2) { //This is isLast plhs[2]=mxCreateLogicalScalar(false); if(nlhs>3) { //This is j. plhs[3]=mxCreateDoubleMatrix(0, 0, mxREAL); } } } return; } //The code array cannot be complex. if(mxIsComplex(prhs[0])!=false) { mexErrMsgTxt("The code array cannot be complex."); } //Copy the code value so that the input matrix is not modified on //return. { size_t n1,n2; n1=mxGetM(prhs[0]); n2=mxGetN(prhs[0]); if((n1==1&&n2>=1)||(n2==1&&n1>=1)) { n=std::max(n1,n2); codeArray=mxDuplicateArray(prhs[0]); } else { mexErrMsgTxt("The code vector has the wrong dimensionality."); } } if(nrhs>1) { nCard=getSizeTFromMatlab(prhs[1]); } else { mxArray *lhs[1]; //Sum up the ones in codeArray to get nCard if it is not provided. mexCallMATLAB(1,lhs,1, &codeArray, "sum"); nCard=getSizeTFromMatlab(lhs[0]); mxDestroyArray(lhs[0]); } //The type of the data in the code array is whatever the user passed to //the function. The function has to be called with the correct template //value for the type of the code. lastPassed=false; switch(mxGetClassID(codeArray)){ case mxCHAR_CLASS: { mxChar *code=(mxChar*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxLOGICAL_CLASS: { mxLogical* code=(mxLogical*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxDOUBLE_CLASS: { double* code=(double*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxSINGLE_CLASS: { float* code=(float*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxINT8_CLASS: { int8_T* code=(int8_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxUINT8_CLASS: { uint8_T* code=(uint8_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxINT16_CLASS: { int16_T* code=(int16_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxUINT16_CLASS: { uint16_T* code=(uint16_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxINT32_CLASS: { int32_T* code=(int32_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxUINT32_CLASS: { uint32_T* code=(uint32_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxINT64_CLASS: { int64_T* code=(int64_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } case mxUINT64_CLASS: { uint64_T* code=(uint64_T*)mxGetData(codeArray); if(nCard==(size_t)code[n-1]&&nCard!=0) { lastPassed=true; } else{ isLast=getNextGrayCodeCPP(n, code, nCard, j); } break; } default: mexErrMsgTxt("The code vector is of an unknown data type."); } //If the final gray code was passed, then just return empty matrices //and put n in nCard. That way, if called again, the function will //start from the beginning. if(lastPassed==true) { mxDestroyArray(codeArray); plhs[0]=mxCreateDoubleMatrix(0, 0, mxREAL); if(nlhs>1) { mxArray *nCardMat=allocUnsignedSizeMatInMatlab(1, 1); *(size_t*)mxGetData(nCardMat)=n; plhs[1]=nCardMat; if(nlhs>2) { //This is isLast plhs[2]=mxCreateDoubleMatrix(0, 0, mxREAL);; if(nlhs>3) { //This is j plhs[3]=mxCreateDoubleMatrix(0, 0, mxREAL);; } } } return; } //Set the return values for the case when the last code was not passed. plhs[0]=codeArray; if(nlhs>1) { mxArray *nCardMat=allocUnsignedSizeMatInMatlab(1, 1); *(size_t*)mxGetData(nCardMat)=nCard; plhs[1]=nCardMat; if(nlhs>2) { //This is isLast plhs[2]=mxCreateLogicalScalar(isLast); if(nlhs>3) { mxArray *jMat=allocUnsignedSizeMatInMatlab(1, 1); //Increment j to be an index for Matlab. j++; *(size_t*)mxGetData(jMat)=j; plhs[3]=jMat; } } } }
/***********************************************************************//** * \brief mexFunction to append a stack to an existing em-file. **************************************************************************/ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) { size_t filename_length = 0; #define __MAX_FILENAME_LENGTH__ ((int)2048) char filename[__MAX_FILENAME_LENGTH__+1]; #define __MAX_S__LENGTH__ (4096) char s[__MAX_S__LENGTH__+1]; #define __BUFFERLENGTH_SYNOPSIS__ 1024 char synopsis[__BUFFERLENGTH_SYNOPSIS__]; size_t i, j, k; const void *w_data; int w_iotype; size_t dims[3]; uint32_t *subregion = NULL; uint32_t subregion_field[6]; tom_io_em_header header; float *complexCopy = 0; char autoval_magic = 1; size_t stridey=0, stridez=0; memset(&header, 0, sizeof(header)); snprintf(synopsis, __BUFFERLENGTH_SYNOPSIS__, "%s(filename, data, [subregion_in, magic, comment, emdata, userdata])", mexFunctionName()); if (nrhs==0 && nlhs==0) { /* Print help */ mexPrintf("SYNOPSIS: %s\n", synopsis); mexPrintf("mex-file compiled from file \"" __FILE__ "\" at " __DATE__ ", " __TIME__ ".\n"); return; } if (nlhs>0 || nrhs<2 || nrhs>7) { snprintf(s, __MAX_S__LENGTH__, "%s: Wrong number of in/output arguments: %s.", mexFunctionName(), synopsis); mexErrMsgTxt(s); } { #define __MAX_UINT32_T__ 0xFFFFFFFF const mxArray *arg; mxArray *tmpArray = NULL; const mwSize *size; double *pdouble; int8_t *pint8; int32_t *pint32; mxClassID type; /* filename */ arg = prhs[0]; if (!mxIsChar(arg) || mxGetNumberOfDimensions(arg)!=2 || mxGetM(arg)!=1 || (filename_length=mxGetN(arg))<1 || filename_length>=__MAX_FILENAME_LENGTH__) { snprintf(s, __MAX_S__LENGTH__, "%s: needs file name as first parameter: %s.", mexFunctionName(), synopsis); mexErrMsgTxt(s); } mxGetString(arg, filename, __MAX_FILENAME_LENGTH__); /* subregion */ if (nrhs >= 3) { arg = prhs[2]; i = mxGetM(arg); j = mxGetN(arg); if (!mxIsNumeric(arg) || mxIsComplex(arg) || mxGetNumberOfDimensions(arg)!=2 || !((i==0&&j==0) || (i==1&&j==6) || (i==6&&j==1))) { snprintf(s, __MAX_S__LENGTH__, "%s: The subregion must be either [] or a 1x6 vector: %s", mexFunctionName(), synopsis); mexErrMsgTxt(s); } if (i!=0) { if (!(tmpArray=getDoubleArray(arg))) { snprintf(s, __MAX_S__LENGTH__, "%s: Error creating a copy of the subregion. Maybe out of memory.", mexFunctionName()); mexErrMsgTxt(s); } pdouble = mxGetPr(tmpArray); for (k=0; k<6; k++) { if (pdouble[k] != floor(pdouble[k]) || pdouble[k]<0 || (k>=3&&pdouble[k]<=0) || pdouble[k]>__MAX_UINT32_T__) { snprintf(s, __MAX_S__LENGTH__, "%s: The subregion must contain positive integer values: %s", mexFunctionName(), synopsis); mexErrMsgTxt(s); } subregion_field[k] = (uint32_t)pdouble[k]; } subregion = subregion_field; mxDestroyArray(tmpArray); } } /* magic */ if (nrhs >= 4) { arg = prhs[3]; if (!mxIsNumeric(arg) || mxIsComplex(arg) || mxGetNumberOfDimensions(arg)!=2) { snprintf(s, __MAX_S__LENGTH__, "%s: magic must be a 4-vector of int8 or [].", mexFunctionName()); mexErrMsgTxt(s); } if (mxGetNumberOfElements(arg) > 0) { if (mxGetClassID(arg)!=mxINT8_CLASS || mxGetNumberOfElements(arg)!=4 || (mxGetN(arg)!=1&&mxGetM(arg)!=1)) { snprintf(s, __MAX_S__LENGTH__, "%s: magic must be a 4-vector of int8 or [].", mexFunctionName()); mexErrMsgTxt(s); } pint8 = (int8_t *)mxGetData(arg); header.machine = pint8[0]; header.byte2 = pint8[1]; header.byte3 = pint8[2]; header.type = pint8[3]; autoval_magic = 0; } } /* comment */ if (nrhs >= 5) { arg = prhs[4]; if (!mxIsNumeric(arg) || mxIsComplex(arg) || mxGetNumberOfDimensions(arg)!=2) { snprintf(s, __MAX_S__LENGTH__, "%s: comment must be a 80-vector of int8 or [].", mexFunctionName()); mexErrMsgTxt(s); } if (mxGetNumberOfElements(arg) > 0) { if (mxGetClassID(arg)!=mxINT8_CLASS || mxGetNumberOfElements(arg)!=80 || (mxGetN(arg)!=1&&mxGetM(arg)!=1)) { snprintf(s, __MAX_S__LENGTH__, "%s: comment must be a 80-vector of int8 or [].", mexFunctionName()); mexErrMsgTxt(s); } pint8 = (int8_t *)mxGetData(arg); for (i=0; i<80; i++) { header.comment[i] = pint8[i]; } } } /* emdata */ if (nrhs >= 6) { arg = prhs[5]; if (!mxIsNumeric(arg) || mxIsComplex(arg) || mxGetNumberOfDimensions(arg)!=2) { snprintf(s, __MAX_S__LENGTH__, "%s: emdata must be a 40-vector of int32 or [].", mexFunctionName()); mexErrMsgTxt(s); } if (mxGetNumberOfElements(arg) > 0) { if (mxGetClassID(arg)!=mxINT32_CLASS || mxGetNumberOfElements(arg)!=40 || (mxGetN(arg)!=1&&mxGetM(arg)!=1)) { snprintf(s, __MAX_S__LENGTH__, "%s: comment must be a 40-vector of int32 or [].", mexFunctionName()); mexErrMsgTxt(s); } pint32 = (int32_t *)mxGetData(arg); for (i=0; i<40; i++) { header.emdata[i] = pint32[i]; } } } /* userdata */ if (nrhs >= 7) { arg = prhs[6]; if (!mxIsNumeric(arg) || mxIsComplex(arg) || mxGetNumberOfDimensions(arg)!=2) { snprintf(s, __MAX_S__LENGTH__, "%s: userdata must be a 256-vector of int8 or [].", mexFunctionName()); mexErrMsgTxt(s); } if (mxGetNumberOfElements(arg) > 0) { if (mxGetClassID(arg)!=mxINT8_CLASS || mxGetNumberOfElements(arg)!=256 || (mxGetN(arg)!=1&&mxGetM(arg)!=1)) { snprintf(s, __MAX_S__LENGTH__, "%s: userdata must be a 256-vector of int8 or [].", mexFunctionName()); mexErrMsgTxt(s); } pint8 = (int8_t *)mxGetData(arg); for (i=0; i<256; i++) { header.userdata[i] = pint8[i]; } } } arg = prhs[1]; if (!mxIsNumeric(arg) || mxGetNumberOfDimensions(arg)>3 || mxGetNumberOfElements(arg)<1) { snprintf(s, __MAX_S__LENGTH__, "%s: The volume must be a non-empty numeric array.", mexFunctionName()); mexErrMsgTxt(s); } size = mxGetDimensions(arg); dims[0] = size[0]; dims[1] = size[1]; dims[2] = mxGetNumberOfDimensions(arg)==3 ? size[2] : 1; type = mxGetClassID(arg); if (mxIsComplex(arg)) { const size_t numel = dims[0]*dims[1]*dims[2]; float *pdst; if (!autoval_magic && tom_io_em_get_iotype(&header)!=TOM_IO_TYPE_COMPLEX4) { snprintf(s, __MAX_S__LENGTH__, "%s: Saving complex data is only possible as complex (single) floating point.", mexFunctionName()); mexErrMsgTxt(s); } if (!(complexCopy = malloc(numel*2*sizeof(float)))) { snprintf(s, __MAX_S__LENGTH__, "%s: Error allocating memory for temporary copy of complex data.", mexFunctionName()); mexErrMsgTxt(s); } pdst = complexCopy; if (type == mxSINGLE_CLASS) { const float *psrc_re, *psrc_im; psrc_re = (float *)mxGetData(arg); psrc_im = (float *)mxGetImagData(arg); for (i=0; i<numel; i++) { *pdst++ = psrc_re[i]; *pdst++ = psrc_im[i]; } } else if (type == mxDOUBLE_CLASS) { const double *psrc_re, *psrc_im; psrc_re = mxGetPr(arg); psrc_im = mxGetPr(arg); for (i=0; i<numel; i++) { *pdst++ = psrc_re[i]; *pdst++ = psrc_im[i]; } } else { free(complexCopy); snprintf(s, __MAX_S__LENGTH__, "%s: EM supports only floating point complex data (single).", mexFunctionName(), type); mexErrMsgTxt(s); } w_iotype = TOM_IO_TYPE_COMPLEX4; w_data = complexCopy; } else { switch (type) { case mxINT8_CLASS: w_iotype = TOM_IO_TYPE_INT8; break; case mxINT16_CLASS: w_iotype = TOM_IO_TYPE_INT16; break; case mxINT32_CLASS: w_iotype = TOM_IO_TYPE_INT32; break; case mxSINGLE_CLASS: w_iotype = TOM_IO_TYPE_FLOAT; break; case mxDOUBLE_CLASS: w_iotype = TOM_IO_TYPE_DOUBLE; break; default: snprintf(s, __MAX_S__LENGTH__, "%s: The volume has type %s: This can not be saved to EM without conversion.", mexFunctionName(), type); mexErrMsgTxt(s); } w_data = mxGetData(arg); } if (subregion) { if (subregion[0]+subregion[3]>dims[0] || subregion[1]+subregion[4]>dims[1] || subregion[2]+subregion[5]>dims[2]) { snprintf(s, __MAX_S__LENGTH__, "%s: The subregion is out of the volume.", mexFunctionName()); mexErrMsgTxt(s); } header.dims[0] = subregion[3]; header.dims[1] = subregion[4]; header.dims[2] = subregion[5]; w_data = (const char *)w_data + ((((subregion[2]*dims[1] + subregion[1]))*dims[0] + subregion[0])*tom_io_iotype_datasize(w_iotype)); stridey = dims[0] * tom_io_iotype_datasize(w_iotype); stridez = dims[1] * stridey; } else { if (dims[0]>=__MAX_UINT32_T__ || dims[1]>=__MAX_UINT32_T__ || dims[2]>=__MAX_UINT32_T__) { snprintf(s, __MAX_S__LENGTH__, "%s: The volume is too large to save it to EM.", mexFunctionName()); mexErrMsgTxt(s); } header.dims[0] = dims[0]; header.dims[1] = dims[1]; header.dims[2] = dims[2]; } if (autoval_magic) { header.machine = 6; tom_io_em_set_iotype(&header, w_iotype); } if (!tom_io_em_is_valid_header(&header, sizeof(header))) { if (complexCopy) { free(complexCopy); } snprintf(s, __MAX_S__LENGTH__, "%s: The given EM-Header is not valid. Check the content of magic.", mexFunctionName()); mexErrMsgTxt(s); } #undef __MAX_UINT32_T__ } { /*printf("WRITE: swapped: %d, %d->%d %20.15f\n", tom_io_em_is_swaped(&header), w_iotype, tom_io_em_get_iotype(&header), *((double *)w_data));*/ int i; if ((i=tom_io_em_write(filename, &header, w_data, w_iotype, 0, stridey, stridez)) != TOM_ERR_OK) { if (complexCopy) { free(complexCopy); } if (i == TOM_ERR_WRONG_IOTYPE_CONVERSION) { snprintf(s, __MAX_S__LENGTH__, "%s: The type conversion from %d to %d is not implemented/supported.", mexFunctionName(), w_iotype, tom_io_em_get_iotype(&header)); } else { snprintf(s, __MAX_S__LENGTH__, "%s: Error saving the file (%d).", mexFunctionName(), i); } mexErrMsgTxt(s); } } if (complexCopy) { free(complexCopy); } }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { mxArray *blk_cell_pr; double *A, *B, *AI, *BI, *blksize; mwIndex *irA, *jcA, *irB, *jcB; int *cumblksize, *blknnz; int mblk, isspA, isspB, iscmpA; mwIndex subs[2]; mwSize nsubs=2; int m, n, n2, nsub, k, index, numblk, NZmax, type; double r2; /* CHECK FOR PROPER NUMBER OF ARGUMENTS */ if (nrhs < 2){ mexErrMsgTxt("mexsvec: requires at least 2 input arguments."); } if (nlhs > 1){ mexErrMsgTxt("mexsvec: requires 1 output argument."); } /* CHECK THE DIMENSIONS */ mblk = mxGetM(prhs[0]); if (mblk > 1) { mexErrMsgTxt("mexsvec: blk can have only 1 row."); } m = mxGetM(prhs[1]); n = mxGetN(prhs[1]); if (m != n) { mexErrMsgTxt("mexsvec: matrix must be square."); } subs[0] = 0; subs[1] = 1; index = mxCalcSingleSubscript(prhs[0],nsubs,subs); blk_cell_pr = mxGetCell(prhs[0],index); numblk = mxGetN(blk_cell_pr); blksize = mxGetPr(blk_cell_pr); if (numblk == 1) { n2 = n*(n+1)/2; } else { cumblksize = mxCalloc(numblk+1,sizeof(int)); blknnz = mxCalloc(numblk+1,sizeof(int)); cumblksize[0] = 0; blknnz[0] = 0; n = 0; n2 = 0; for (k=0; k<numblk; ++k) { nsub = (int) blksize[k]; n += nsub; n2 += nsub*(nsub+1)/2; cumblksize[k+1] = n; blknnz[k+1] = n2; } } /***** assign pointers *****/ A = mxGetPr(prhs[1]); isspA = mxIsSparse(prhs[1]); iscmpA = mxIsComplex(prhs[1]); if (isspA) { irA = mxGetIr(prhs[1]); jcA = mxGetJc(prhs[1]); NZmax = mxGetNzmax(prhs[1]); } else { NZmax = n2; } if (iscmpA) { AI = mxGetPi(prhs[1]); } if ((numblk > 1) & (!isspA)) { mexErrMsgTxt("mexsvec: matrix must be sparse for numblk > 1"); } if (nrhs > 2) { if (mxGetM(prhs[2])>1) { isspB = (int)*mxGetPr(prhs[2]); } else if (NZmax < n2/2) { isspB = 1; } else { isspB = 0; } } else { if (NZmax < n2/2) { isspB = 1; } else { isspB = 0; } } if (nrhs > 3) { type = (int)*mxGetPr(prhs[3]); } else { type = 0; } /***** create return argument *****/ if (isspB) { if (iscmpA) { plhs[0] = mxCreateSparse(n2,1,NZmax,mxCOMPLEX); } else { plhs[0] = mxCreateSparse(n2,1,NZmax,mxREAL); } B = mxGetPr(plhs[0]); irB = mxGetIr(plhs[0]); jcB = mxGetJc(plhs[0]); jcB[0] = 0; } else { if (iscmpA) { plhs[0] = mxCreateDoubleMatrix(n2,1,mxCOMPLEX); } else { plhs[0] = mxCreateDoubleMatrix(n2,1,mxREAL); } B = mxGetPr(plhs[0]); } if (iscmpA) { BI = mxGetPi(plhs[0]); } /***** Do the computations in a subroutine *****/ r2 = sqrt(2); if (type == 0) { if (iscmpA) { if (numblk == 1) { svec1cmp(n,r2,A,irA,jcA,isspA,B,irB,jcB,isspB,AI,BI); } else { svec2cmp(n,numblk,cumblksize,blknnz,r2,A,irA,jcA,isspA,B,irB,jcB,isspB,AI,BI); } } else { if (numblk == 1) { svec1(n,r2,A,irA,jcA,isspA,B,irB,jcB,isspB); } else { svec2(n,numblk,cumblksize,blknnz,r2,A,irA,jcA,isspA,B,irB,jcB,isspB); } } } else { if (iscmpA) { if (numblk == 1) { svec3cmp(n,r2,A,irA,jcA,isspA,B,irB,jcB,isspB,AI,BI); } else { svec4cmp(n,numblk,cumblksize,blknnz,r2,A,irA,jcA,isspA,B,irB,jcB,isspB,AI,BI); } } else { if (numblk == 1) { svec3(n,r2,A,irA,jcA,isspA,B,irB,jcB,isspB); } else { svec4(n,numblk,cumblksize,blknnz,r2,A,irA,jcA,isspA,B,irB,jcB,isspB); } } } return; }
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { mxClassID classid; mxArray *Amx, *Bmx; mwSize Adims[12] = {1,1,1,1,1,1,1,1,1,1,1,1}; mwSize Bdims[12] = {1,1,1,1,1,1,1,1,1,1,1,1}; mwSize Cdims[12]; int Andim, Bndim, Cndim; mxComplexity complexity; void *Apr, *Api, *Cpr, *Cpi; int i; // Check for bit length definitions if( sizeof(bit16) != 2 ) mexErrMsgTxt("Error using bsxarg: bit16 length is not 16-bits."); if( sizeof(bit32) != 4 ) mexErrMsgTxt("Error using bsxarg: bit32 length is not 32-bits."); if( sizeof(bit64) != 8 ) mexErrMsgTxt("Error using bsxarg: bit64 length is not 64-bits."); // Check for proper inputs if( nrhs != 2 ) mexErrMsgTxt("Error using bsxarg: Invalid number of inputs. Need two."); if( nlhs > 2 ) mexErrMsgTxt("Error using bsxarg: Invalid number of outputs. Not more than two."); // Set temporary operand pointers to the inputs. Amx = const_cast<mxArray*>(prhs[0]); Bmx = const_cast<mxArray*>(prhs[1]); // Check for supported operand classes switch( mxGetClassID(Amx) ) { case mxDOUBLE_CLASS: case mxINT64_CLASS: case mxUINT64_CLASS: case mxSINGLE_CLASS: case mxINT32_CLASS: case mxUINT32_CLASS: case mxCHAR_CLASS: case mxINT16_CLASS: case mxUINT16_CLASS: case mxLOGICAL_CLASS: case mxINT8_CLASS: case mxUINT8_CLASS: break; default: mexErrMsgTxt("Error using bsxarg: 1st argument class not supported"); } switch( mxGetClassID(Bmx) ) { case mxDOUBLE_CLASS: case mxINT64_CLASS: case mxUINT64_CLASS: case mxSINGLE_CLASS: case mxINT32_CLASS: case mxUINT32_CLASS: case mxCHAR_CLASS: case mxINT16_CLASS: case mxUINT16_CLASS: case mxLOGICAL_CLASS: case mxINT8_CLASS: case mxUINT8_CLASS: break; default: mexErrMsgTxt("Error using bsxarg: 2nd argument class not supported"); } // Generate the indexing multipliers Andim = mxGetNumberOfDimensions(Amx); if( Andim > 12 ) mexErrMsgTxt("Error using bsxarg: 1st array argument has too many dimensions."); memcpy(Adims, mxGetDimensions(Amx), Andim*sizeof(mwSize)); A1 = 1; A2 = Adims[0]; A3 = Adims[1]*A2; A4 = Adims[2]*A3; A5 = Adims[3]*A4; A6 = Adims[4]*A5; A7 = Adims[5]*A6; A8 = Adims[6]*A7; A9 = Adims[7]*A8; A10 = Adims[8]*A9; A11 = Adims[9]*A10; A12 = Adims[10]*A11; if( Adims[0] < 2 ) A1 = 0; if( Adims[1] < 2 ) A2 = 0; if( Adims[2] < 2 ) A3 = 0; if( Adims[3] < 2 ) A4 = 0; if( Adims[4] < 2 ) A5 = 0; if( Adims[5] < 2 ) A6 = 0; if( Adims[6] < 2 ) A7 = 0; if( Adims[7] < 2 ) A8 = 0; if( Adims[8] < 2 ) A9 = 0; if( Adims[9] < 2 ) A10 = 0; if( Adims[10] < 2 ) A11 = 0; if( Adims[11] < 2 ) A12 = 0; Bndim = mxGetNumberOfDimensions(Bmx); if( Bndim > 12 ) mexErrMsgTxt("Error using bsxarg: 2nd array argument has too many dimensions."); memcpy(Bdims, mxGetDimensions(Bmx), Bndim*sizeof(mwSize)); B1 = 1; B2 = Bdims[0]; B3 = Bdims[1]*B2; B4 = Bdims[2]*B3; B5 = Bdims[3]*B4; B6 = Bdims[4]*B5; B7 = Bdims[5]*B6; B8 = Bdims[6]*B7; B9 = Bdims[7]*B8; B10 = Bdims[8]*B9; B11 = Bdims[9]*B10; B12 = Bdims[10]*B11; if( Bdims[0] < 2 ) B1 = 0; if( Bdims[1] < 2 ) B2 = 0; if( Bdims[2] < 2 ) B3 = 0; if( Bdims[3] < 2 ) B4 = 0; if( Bdims[4] < 2 ) B5 = 0; if( Bdims[5] < 2 ) B6 = 0; if( Bdims[6] < 2 ) B7 = 0; if( Bdims[7] < 2 ) B8 = 0; if( Bdims[8] < 2 ) B9 = 0; if( Bdims[9] < 2 ) B10 = 0; if( Bdims[10] < 2 ) B11 = 0; if( Bdims[11] < 2 ) B12 = 0; k1 = MAX( Adims[0], Bdims[0] ); k2 = MAX( Adims[1], Bdims[1] ); k3 = MAX( Adims[2], Bdims[2] ); k4 = MAX( Adims[3], Bdims[3] ); k5 = MAX( Adims[4], Bdims[4] ); k6 = MAX( Adims[5], Bdims[5] ); k7 = MAX( Adims[6], Bdims[6] ); k8 = MAX( Adims[7], Bdims[7] ); k9 = MAX( Adims[8], Bdims[8] ); k10 = MAX( Adims[9], Bdims[9] ); k11 = MAX( Adims[10], Bdims[10] ); k12 = MAX( Adims[11], Bdims[11] ); for( i=0; i<12; i++ ) { if( Adims[i] != Bdims[i] && Adims[i] != 1 && Bdims[i] != 1 ) mexErrMsgTxt("Error using bsxarg: All non-singleton dimensions must match."); Cdims[i] = (Adims[i] && Bdims[i]) ? MAX( Adims[i], Bdims[i] ) : 0; } Cndim = MAX( Andim, Bndim ); // Fill in the values --------------------------------------------------------- classid = mxGetClassID(prhs[0]); complexity = mxIsComplex(prhs[0]) ? mxCOMPLEX : mxREAL; plhs[0] = mxCreateNumericArray(Cndim, Cdims, classid, complexity); if( mxGetNumberOfElements(plhs[0]) ) { Cpr = mxGetData(plhs[0]); Cpi = mxGetImagData(plhs[0]); Apr = mxGetData(prhs[0]); Api = mxGetImagData(prhs[0]); switch( classid ) { case mxDOUBLE_CLASS: case mxINT64_CLASS: case mxUINT64_CLASS: expand_64bits(Cpr, Cpi, Apr, Api, complexity); break; case mxSINGLE_CLASS: case mxINT32_CLASS: case mxUINT32_CLASS: expand_32bits(Cpr, Cpi, Apr, Api, complexity); break; case mxCHAR_CLASS: case mxINT16_CLASS: case mxUINT16_CLASS: expand_16bits(Cpr, Cpi, Apr, Api, complexity); break; case mxLOGICAL_CLASS: case mxINT8_CLASS: case mxUINT8_CLASS: expand_8bits(Cpr, Cpi, Apr, Api, complexity); break; } } if( nlhs < 2 ) return; classid = mxGetClassID(prhs[1]); complexity = mxIsComplex(prhs[1]) ? mxCOMPLEX : mxREAL; plhs[1] = mxCreateNumericArray(Cndim, Cdims, classid, complexity); if( mxGetNumberOfElements(plhs[1]) ) { Cpr = mxGetData(plhs[1]); Cpi = mxGetImagData(plhs[1]); Apr = mxGetData(prhs[1]); Api = mxGetImagData(prhs[1]); A1 = B1; A2 = B2; A3 = B3; A4 = B4; A5 = B5; A6 = B6; A7 = B7; A8 = B8; A9 = B9; A10 = B10; A11 = B11; A12 = B12; switch( classid ) { case mxDOUBLE_CLASS: case mxINT64_CLASS: case mxUINT64_CLASS: expand_64bits(Cpr, Cpi, Apr, Api, complexity); break; case mxSINGLE_CLASS: case mxINT32_CLASS: case mxUINT32_CLASS: expand_32bits(Cpr, Cpi, Apr, Api, complexity); break; case mxCHAR_CLASS: case mxINT16_CLASS: case mxUINT16_CLASS: expand_16bits(Cpr, Cpi, Apr, Api, complexity); break; case mxLOGICAL_CLASS: case mxINT8_CLASS: case mxUINT8_CLASS: expand_8bits(Cpr, Cpi, Apr, Api, complexity); break; } } }
void PPDEVWrite(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int numAddresses = 1, numVals = 8, i, j, result, addrStrLen, port; uint8_T *data; mxArray *tmp; uint64_T val; mxLogical *out; uint8_T bitNum, regOffset, value = 0; unsigned char mask[NUM_REGISTERS] = { 0 }, vals[NUM_REGISTERS] = { 0 }, pos; bool writing = true; /* Check number of input arguments */ if (nrhs != 2) { mexErrMsgTxt("Exactly 2 arguments required."); } /* The device number and value must be noncomplex scalar double */ for (i = 0; i < nrhs; i++) { /* if (!mxIsDouble(prhs[i]) || mxIsComplex(prhs[i]) || ! mxIsScalar(prhs[i])) { */ if (!mxIsDouble(prhs[i]) || mxIsComplex(prhs[i]) || !(mxGetN(prhs[i])==1 && mxGetM(prhs[i])==1)) { mexErrMsgTxt("Arguments must be noncomplex scalar double."); } } /* Assign pointers to each input */ port = *mxGetPr(prhs[0]); if (port < 1 || port > MAX_DEVS) { mexErrMsgTxt("Port number out of range."); } port--; val = *mxGetPr(prhs[1]); if (val < 0 || val > 255) { mexErrMsgTxt("Value out of range."); } /* Convert value to data/bit matrix */ tmp = mxCreateNumericMatrix(8, 3, mxUINT8_CLASS, mxREAL); data = mxGetData(tmp); for (i = 0; i < numVals; i++) { data[i] = i; data[i + numVals] = 0; data[i + 2 * numVals] = getBit(val, i); } /* Assign pointers to each output */ if (DEBUG) printf("%d lhs\n",nlhs); switch (nlhs) { case 1: *plhs = mxCreateLogicalMatrix(numVals,numAddresses); if (*plhs == NULL) { mexErrMsgTxt("couldn't allocate output"); } out = mxGetLogicals(*plhs); break; case 0: if (!writing) { mexErrMsgTxt("exactly 1 output argument required when reading"); } out = NULL; break; default: mexErrMsgTxt("at most 1 output argument allowed"); break; } if (DEBUG) printf("\n\ndata:\n"); /* Convert data matrix for use with doPort */ for (i = 0; i < numVals; i++) { bitNum = data[i ]; regOffset = data[i+ numVals]; if (writing) { value = data[i+2*numVals]; } if (DEBUG) { printf("\t%d, %d", bitNum, regOffset); if (writing) printf(" %d", value); printf("\n"); } if (bitNum>7 || regOffset>2 || value>1) { mexErrMsgTxt("bitNum must be 0-7, regOffset must be 0-2, value must be 0-1."); } pos = 1<<bitNum; mask[regOffset] |= pos; if (value) vals[regOffset] |= pos; } if (DEBUG) { for (j = 0; j < NUM_REGISTERS; j++) { printf("mask:"); printBits(mask[j]); if (writing) { printf(" val:"); printBits(vals[j]); } printf("\n"); } } i = 0; if (ppdev_table[port] != NULL) { doPort(ppdev_table[port]->addr, ppdev_table[port]->parportfd, mask, vals, out, i, data, numVals, writing); } else { mexErrMsgTxt("Port not open."); } }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { double *tr,*ti; double *cr,*ci,*rr,*ri; mwSize tm,tn; /* Check for proper number of arguments */ if (nrhs > 2) { mexErrMsgTxt("More than 2 input arguments."); } else if (nrhs == 0) { mexErrMsgTxt("1 or 2 input arguments required."); } else if (nrhs == 1) { mexErrMsgTxt("1 input argument: not implemented (yet), use toeplitz."); } else if (nlhs > 1) { mexErrMsgTxt("Too many output arguments."); } if (nrhs == 1) { mexErrMsgTxt("Not implemented (yet). Please use 2 input arguments or toeplitz.m with one input argument."); } /* Check the dimensions of Y. Y can be 4 X 1 or 1 X 4. */ tm = mxGetNumberOfElements(C_IN); tn = mxGetNumberOfElements(R_IN); /* Create a matrix for the return argument */ if (mxIsComplex(C_IN) || mxIsComplex(R_IN)) T_OUT = mxCreateDoubleMatrix(tm, tn, mxCOMPLEX); else T_OUT = mxCreateDoubleMatrix(tm, tn, mxREAL); /* Assign pointers to the various parameters */ tr = mxGetPr(T_OUT); cr = mxGetPr(C_IN); rr = mxGetPr(R_IN); /* Do the actual computations in a subroutine */ toeplitzC(tr,cr,rr,tm,tn); /* Imaginary part */ if (mxIsComplex(C_IN) || mxIsComplex(R_IN)) { /*if (!mxIsComplex(C_IN)){ mexErrMsgTxt("Not implemented (yet). A"); } else*/ if (mxIsComplex(C_IN)) ci = mxGetPi(C_IN); else ci = mxGetPr(mxCreateDoubleMatrix(tm, 1, mxREAL)); /*if (!mxIsComplex(R_IN)){ mexErrMsgTxt("Not implemented (yet). B"); } else*/ if (mxIsComplex(R_IN)) ri = mxGetPi(R_IN); else ri = mxGetPr(mxCreateDoubleMatrix(tn, 1, mxREAL)); ti = mxGetPi(T_OUT); toeplitzC(ti, ci, ri, tm, tn); } return; }
void PPDEVOpen(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int result, addrStrLen; uint64_T port; char *addrStr; pp_device *newdev = NULL; /* The device number must be noncomplex scalar double */ /* if (nrhs != 1 || !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !mxIsScalar(prhs[0])) { */ if (nrhs != 1 || !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mxGetN(prhs[0])==1 && mxGetM(prhs[0])==1)) { mexErrMsgTxt("Port number must be noncomplex scalar double."); } /* Assign pointers to each input */ port = *mxGetPr(prhs[0]); if (port < 1 || port > MAX_DEVS) { mexErrMsgTxt("Port number out of range."); } port--; /* Convert port number to string file name */ addrStrLen = strlen(ADDR_BASE) + (port == 0 ? 1 : 1 + floor(log10(port))); /* number digits in port */ addrStr = (char *)mxMalloc(addrStrLen + 1); if (addrStr == NULL) { mexErrMsgTxt("couldn't allocate addrStr"); } mexMakeMemoryPersistent(addrStr); /* result = snprintf(addrStr,addrStrLen+1,"%s%" FMT64 "u",ADDR_BASE,port); /* +1 for null terminator */ result = snprintf(addrStr,addrStrLen+1,"%s%lu",ADDR_BASE,port); /* +1 for null terminator */ if (result != addrStrLen) { printf("%d\t%d\t%s\n",result,addrStrLen,addrStr); mexErrMsgTxt("bad addrStr snprintf"); } if (DEBUG) printf("%d\t%s.\n",addrStrLen,addrStr); /* Allocate memory for new port device */ newdev = (pp_device *)mxMalloc(sizeof(pp_device)); mexMakeMemoryPersistent(newdev); if (newdev != NULL) { mexAtExit(PPDEVCloseAll); newdev->addr = addrStr; /* Open port and get file descriptor */ newdev->parportfd = open(newdev->addr, O_RDWR); if (newdev->parportfd == -1) { printf("%s %s\n",newdev->addr,strerror(errno)); mexErrMsgTxt("couldn't access port"); } /*bug: if the following error out, we won't close parportfd or free addrStr -- need some exceptionish error handling * AW: We can close port and free memory in PPDEVCLose(All). Solved? /* PPEXCL call succeeds, but causes following calls to fail * then dmesg has: parport0: cannot grant exclusive access for device ppdev0 * ppdev0: failed to register device! * * web search suggests this is because lp is loaded -- implications of removing it? * AW: Did not notice any side effects yet */ /* We want exclusive access for triggering */ ppd(newdev->parportfd,PPEXCL,NULL,"couldn't get exclusive access to pport"); /* Claim port and set byte mode */ ppd(newdev->parportfd,PPCLAIM,NULL,"couldn't claim pport"); int mode = IEEE1284_MODE_BYTE; /* or would we want COMPAT? */ ppd(newdev->parportfd,PPSETMODE,&mode,"couldn't set byte mode"); newdev->claimed = true; ppdev_table[0] = newdev; } else { mexErrMsgTxt("Could not allocate memory for new device"); } }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int taglen, status, argc=2, i, ndim, len; const int *dim=NULL; size_t nbuf = BUFSIZ, nd, j; char *tag=NULL, *argv[] = {"matlab","-"}, *par=NULL, *filename=NULL; double *dr=NULL, *di=NULL; float *p=NULL; sf_complex *c=NULL; char buf[BUFSIZ], key[5]; bool same; FILE *file2=NULL; sf_file file=NULL; /* Check for proper number of arguments. */ if (nrhs < 2 || nrhs > 3) mexErrMsgTxt("Two or three inputs required."); /* Second input must be a string. */ if (!mxIsChar(prhs[1])) mexErrMsgTxt("Second input must be a string."); /* Second input must be a row vector. */ if (mxGetM(prhs[1]) != 1) mexErrMsgTxt("Second input must be a row vector."); /* Get the length of the input string. */ taglen = mxGetN(prhs[1]) + 1; /* Allocate memory for input string. */ tag = mxCalloc(taglen, sizeof(char)); /* Copy the string data from prhs[1] into a C string. */ status = mxGetString(prhs[1], tag, taglen); if (status != 0) mexWarnMsgTxt("Not enough space. String is truncated."); if (3 == nrhs) { /* Input 3 must be a string. */ if (!mxIsChar(prhs[2])) mexErrMsgTxt("Input 3 must be a string."); /* Input 3 must be a row vector. */ if (mxGetM(prhs[2]) != 1) mexErrMsgTxt("Input 3 must be a row vector."); /* Get the length of the input string. */ len = mxGetN(prhs[2]) + 1; /* Allocate memory for input string. */ par = mxCalloc(len, sizeof(char)); /* Copy the string data from prhs[2] into a C string. */ status = mxGetString(prhs[2], par, len); if (status != 0) mexWarnMsgTxt("Not enough space. String is truncated."); same = (0 == (strncmp(par,"same",4))); } else { same = false; } sf_init(argc,argv); if (same) { file = sf_input(tag); filename = sf_histstring(file,"in"); sf_fileclose(file); if (NULL == filename) mexErrMsgTxt("No in= in file."); file2 = fopen(filename,"ab"); if (NULL == file2) mexErrMsgTxt("Could not open binary file for writing."); } else { file = sf_output(tag); file2 = NULL; } /* Input 1 must be a number. */ if (!mxIsDouble(prhs[0])) mexErrMsgTxt("First input must be double."); /* get data dimensions */ ndim=mxGetNumberOfDimensions(prhs[0]); dim=mxGetDimensions(prhs[0]); /* get data size */ nd = mxGetNumberOfElements(prhs[0]); if (!same) { sf_setformat(file,mxIsComplex(prhs[0])?"native_complex":"native_float"); /* Output */ for (i=0; i < ndim; i++) { sprintf(key,"n%d",i+1); sf_putint(file,key,dim[i]); } } if (mxIsComplex(prhs[0])) { /* complex data */ c = (sf_complex*) buf; dr = mxGetPr(prhs[0]); /* pointer to imaginary part */ di = mxGetPi(prhs[0]); for (j=0, nbuf /= sizeof(sf_complex); nd > 0; nd -= nbuf) { if (nbuf > nd) nbuf=nd; for (i=0; i < nbuf; i++, j++) { c[i] = sf_cmplx((float) dr[j],(float) di[j]); } if (same) { if (nbuf != fwrite(c,sizeof(sf_complex),nbuf,file2)) mexWarnMsgTxt("Writing problems."); } else { sf_complexwrite(c,nbuf,file); } } } else { /* real data */ p = (float*) buf; dr = mxGetPr(prhs[0]); for (j=0, nbuf /= sizeof(float); nd > 0; nd -= nbuf) { if (nbuf > nd) nbuf=nd; for (i=0; i < nbuf; i++, j++) { p[i] = (float) dr[j]; } if (same) { if (nbuf != fwrite(p,sizeof(float),nbuf,file2)) mexWarnMsgTxt("Writing problems."); } else { sf_floatwrite(p,nbuf,file); } } } if (same) { fclose(file2); } else { sf_fileclose(file); } }
// Takes a MATLAB variable and writes in in Mathematica form to link void toMma(const mxArray *var, MLINK link) { // the following may occur when retrieving empty struct fields // it showsup as [] in MATLAB so we return {} // note that non-existent variables are caught and handled in eng_get() if (var == NULL) { MLPutFunction(link, "List", 0); return; } // get size information mwSize depth = mxGetNumberOfDimensions(var); const mwSize *mbDims = mxGetDimensions(var); // handle zero-size arrays if (mxIsEmpty(var)) { if (mxIsChar(var)) MLPutString(link, ""); else MLPutFunction(link, "List", 0); return; } // translate dimension information to Mathematica order std::vector<int> mmDimsVec(depth); std::reverse_copy(mbDims, mbDims + depth, mmDimsVec.begin()); int *mmDims = &mmDimsVec[0]; int len = mxGetNumberOfElements(var); // numerical (sparse or dense) if (mxIsNumeric(var)) { mxClassID classid = mxGetClassID(var); // verify that var is of a supported class switch (classid) { case mxDOUBLE_CLASS: case mxSINGLE_CLASS: case mxINT32_CLASS: case mxINT16_CLASS: case mxUINT16_CLASS: case mxINT8_CLASS: case mxUINT8_CLASS: break; default: putUnknown(var, link); return; } if (mxIsSparse(var)) { // Note: I realised that sparse arrays can only hold double precision numerical types // in MATLAB R2013a. I will leave the below implementation for single precision & integer // types in case future versions of MATLAB will add support for them. int ncols = mxGetN(var); // number of columns mwIndex *jc = mxGetJc(var); mwIndex *ir = mxGetIr(var); int nnz = jc[ncols]; // number of nonzeros MLPutFunction(link, CONTEXT "matSparseArray", 4); mlpPutIntegerList(link, jc, ncols + 1); mlpPutIntegerList(link, ir, nnz); // if complex, put as im*I + re if (mxIsComplex(var)) { MLPutFunction(link, "Plus", 2); MLPutFunction(link, "Times", 2); MLPutSymbol(link, "I"); switch (classid) { case mxDOUBLE_CLASS: MLPutReal64List(link, mxGetPi(var), nnz); break; case mxSINGLE_CLASS: MLPutReal32List(link, (float *) mxGetImagData(var), nnz); break; case mxINT16_CLASS: MLPutInteger16List(link, (short *) mxGetImagData(var), nnz); break; case mxINT32_CLASS: MLPutInteger32List(link, (int *) mxGetImagData(var), nnz); break; default: assert(false); // should never reach here } } switch (classid) { case mxDOUBLE_CLASS: MLPutReal64List(link, mxGetPr(var), nnz); break; case mxSINGLE_CLASS: MLPutReal32List(link, (float *) mxGetData(var), nnz); break; case mxINT16_CLASS: MLPutInteger16List(link, (short *) mxGetData(var), nnz); break; case mxINT32_CLASS: MLPutInteger32List(link, (int *) mxGetData(var), nnz); break; default: assert(false); // should never reach here } MLPutInteger32List(link, mmDims, depth); } else // not sparse { MLPutFunction(link, CONTEXT "matArray", 2); // if complex, put as im*I + re if (mxIsComplex(var)) { MLPutFunction(link, "Plus", 2); MLPutFunction(link, "Times", 2); MLPutSymbol(link, "I"); switch (classid) { case mxDOUBLE_CLASS: MLPutReal64Array(link, mxGetPi(var), mmDims, NULL, depth); break; case mxSINGLE_CLASS: MLPutReal32Array(link, (float *) mxGetImagData(var), mmDims, NULL, depth); break; case mxINT32_CLASS: MLPutInteger32Array(link, (int *) mxGetImagData(var), mmDims, NULL, depth); break; case mxINT16_CLASS: MLPutInteger16Array(link, (short *) mxGetImagData(var), mmDims, NULL, depth); break; case mxUINT16_CLASS: { int *arr = new int[len]; unsigned short *mbData = (unsigned short *) mxGetImagData(var); std::copy(mbData, mbData + len, arr); MLPutInteger32Array(link, arr, mmDims, NULL, depth); delete [] arr; break; } case mxINT8_CLASS: { short *arr = new short[len]; char *mbData = (char *) mxGetImagData(var); std::copy(mbData, mbData + len, arr); MLPutInteger16Array(link, arr, mmDims, NULL, depth); delete [] arr; break; } case mxUINT8_CLASS: { short *arr = new short[len]; unsigned char *mbData = (unsigned char *) mxGetImagData(var); std::copy(mbData, mbData + len, arr); MLPutInteger16Array(link, arr, mmDims, NULL, depth); delete [] arr; break; } default: assert(false); // should never reach here } } switch (classid) { case mxDOUBLE_CLASS: MLPutReal64Array(link, mxGetPr(var), mmDims, NULL, depth); break; case mxSINGLE_CLASS: MLPutReal32Array(link, (float *) mxGetData(var), mmDims, NULL, depth); break; case mxINT32_CLASS: MLPutInteger32Array(link, (int *) mxGetData(var), mmDims, NULL, depth); break; case mxINT16_CLASS: MLPutInteger16Array(link, (short *) mxGetData(var), mmDims, NULL, depth); break; case mxUINT16_CLASS: { int *arr = new int[len]; unsigned short *mbData = (unsigned short *) mxGetData(var); std::copy(mbData, mbData + len, arr); MLPutInteger32Array(link, arr, mmDims, NULL, depth); delete [] arr; break; } case mxINT8_CLASS: { short *arr = new short[len]; char *mbData = (char *) mxGetData(var); std::copy(mbData, mbData + len, arr); MLPutInteger16Array(link, arr, mmDims, NULL, depth); delete [] arr; break; } case mxUINT8_CLASS: { short *arr = new short[len]; unsigned char *mbData = (unsigned char *) mxGetData(var); std::copy(mbData, mbData + len, arr); MLPutInteger16Array(link, arr, mmDims, NULL, depth); delete [] arr; break; } default: assert(false); // should never reach here } MLPutInteger32List(link, mmDims, depth); } } // logical (sparse or dense) else if (mxIsLogical(var)) if (mxIsSparse(var)) { int ncols = mxGetN(var); // number of columns mwIndex *jc = mxGetJc(var); mwIndex *ir = mxGetIr(var); mxLogical *logicals = mxGetLogicals(var); int nnz = jc[ncols]; // number of nonzeros MLPutFunction(link, CONTEXT "matSparseLogical", 4); mlpPutIntegerList(link, jc, ncols + 1); mlpPutIntegerList(link, ir, nnz); short *integers = new short[nnz]; std::copy(logicals, logicals+nnz, integers); MLPutInteger16List(link, integers, nnz); MLPutInteger32List(link, mmDims, depth); delete [] integers; } else // not sparse { mxLogical *logicals = mxGetLogicals(var); short *integers = new short[len]; std::copy(logicals, logicals+len, integers); MLPutFunction(link, CONTEXT "matLogical", 2); MLPutInteger16Array(link, integers, mmDims, NULL, depth); MLPutInteger32List(link, mmDims, depth); delete [] integers; } // char array else if (mxIsChar(var)) { assert(sizeof(mxChar) == sizeof(unsigned short)); // 1 by N char arrays (row vectors) are sent as a string if (depth == 2 && mbDims[0] == 1) { const mxChar *str = mxGetChars(var); MLPutFunction(link, CONTEXT "matString", 1); MLPutUTF16String(link, reinterpret_cast<const unsigned short *>(str), len); // cast may be required on other platforms: (mxChar *) str } // general char arrays are sent as an array of characters else { MLPutFunction(link, CONTEXT "matCharArray", 2); const mxChar *str = mxGetChars(var); MLPutFunction(link, "List", len); for (int i=0; i < len; ++i) MLPutUTF16String(link, reinterpret_cast<const unsigned short *>(str + i), 1); MLPutInteger32List(link, mmDims, depth); } } // struct else if (mxIsStruct(var)) { int nfields = mxGetNumberOfFields(var); MLPutFunction(link, CONTEXT "matStruct", 2); MLPutFunction(link, "List", len); for (int j=0; j < len; ++j) { MLPutFunction(link, "List", nfields); for (int i=0; i < nfields; ++i) { const char *fieldname; fieldname = mxGetFieldNameByNumber(var, i); MLPutFunction(link, "Rule", 2); MLPutString(link, fieldname); toMma(mxGetFieldByNumber(var, j, i), link); } } MLPutInteger32List(link, mmDims, depth); } // cell else if (mxIsCell(var)) { MLPutFunction(link, CONTEXT "matCell", 2); MLPutFunction(link, "List", len); for (int i=0; i < len; ++i) toMma(mxGetCell(var, i), link); MLPutInteger32List(link, mmDims, depth); } // unknown or failure; TODO distinguish between unknown and failure else { putUnknown(var, link); } }
/* * The mex function runs a max-flow min-cut problem. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int i; int mrows, ncols; int n,nz; /* sparse matrix */ mwIndex *ia, *ja; /* output data */ double *a, *ci; mwIndex *int_a; if (nrhs != 1) { mexErrMsgTxt("1 inputs required."); } /* The first input must be a sparse matrix. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if (mrows != ncols || !mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) { mexErrMsgTxt("Input must be a noncomplex square sparse matrix."); } n = mrows; /* Get the sparse matrix */ /* recall that we've transposed the matrix */ ja = mxGetIr(prhs[0]); ia = mxGetJc(prhs[0]); nz = ia[n]; plhs[0] = mxCreateDoubleMatrix(n,1,mxREAL); a = mxGetPr(plhs[0]); ci = NULL; if (nlhs > 1) { plhs[1] = mxCreateDoubleMatrix(nz,1,mxREAL); ci = mxGetPr(plhs[1]); } int_a = (mwIndex*)a; for (i=0; i<n; i++) { int_a[i] = MWINDEX_MAX; } biconnected_components(n, ja, ia, (mwIndex*)a, (mwIndex*)ci); expand_index_to_double_zero_special((mwIndex*)a, a, n, 1.0, MWINDEX_MAX); if (nlhs > 1) { expand_index_to_double((mwIndex*)ci, ci, nz, 1.0); } }
void mexFunction ( int nargout, mxArray *pargout[ ], int nargin, const mxArray *pargin[ ] ) { Long i, n, *Pattern, *Flag, *Li, *Lp, *Ap, *Ai, *Lnz, *Parent, lnz, do_num_only, *P, *Pinv, nn, k, j, permute, *Dp = NULL, *Di, d, psrc, pdst ; double *Y, *D, *Lx, *Ax, *p, *lp ; /* ---------------------------------------------------------------------- */ /* get inputs and allocate workspace */ /* ---------------------------------------------------------------------- */ do_num_only = ((nargin == 5) || (nargin == 7)) && (nargout <= 2) ; if (!do_num_only) { mexErrMsgTxt ("Usage:\n" " [L, D] = ldlsparse (A, Lp, Lnz, Parent, Flag) ;\n" " [L, D] = ldlsparse (A, Lp, Lnz, Parent, Flag, P, PInv)") ; } n = mxGetM (pargin [0]) ; if (!mxIsSparse (pargin [0]) || n != mxGetN (pargin [0]) || mxIsComplex (pargin [0])) { mexErrMsgTxt ("ldl: A must be sparse, square, and real") ; } nn = (n == 0) ? 1 : n ; /* get sparse matrix A */ Ap = (Long *) mxGetJc (pargin [0]) ; Ai = (Long *) mxGetIr (pargin [0]) ; Ax = mxGetPr (pargin [0]) ; /* get Lp */ if (mxGetM (pargin [1]) * mxGetN (pargin [1]) != (n+1) || mxIsSparse (pargin [1])) { mexErrMsgTxt ("ldl: invalid input Lp\n") ; } Lp = (Long *) mxMalloc ((n+1) * sizeof (Long)) ; lp = mxGetPr (pargin [1]) ; for (k = 0 ; k < (n+1) ; k++) { Lp [k] = lp [k]; } /* get Lnz */ /* if (mxGetM (pargin [2]) * mxGetN (pargin [2]) != n || mxIsSparse (pargin [2])) { mexErrMsgTxt ("ldl: invalid input Lnz\n") ; }*/ Lnz = (Long *) mxMalloc (nn * sizeof (Long)) ; /*p = mxGetPr (pargin [2]) ; for (k = 0 ; k < n ; k++) { Lnz [k] = p [k]; }*/ /* get Parent */ if (mxGetM (pargin [3]) * mxGetN (pargin [3]) != n || mxIsSparse (pargin [3])) { mexErrMsgTxt ("ldl: invalid input Parent\n") ; } Parent = (Long *) mxMalloc (nn * sizeof (Long)) ; p = mxGetPr (pargin [3]) ; for (k = 0 ; k < n ; k++) { Parent [k] = p [k]; } /* get Flag */ /*if (mxGetM (pargin [4]) * mxGetN (pargin [4]) != n || mxIsSparse (pargin [4])) { mexErrMsgTxt ("ldl: invalid input Flag\n") ; }*/ Flag = (Long *) mxMalloc (nn * sizeof (Long)) ; /*p = mxGetPr (pargin [4]) ; for (k = 0 ; k < n ; k++) { Flag [k] = p [k]; }*/ /* get fill-reducing ordering, if present */ permute = ((nargin == 7) && !mxIsEmpty (pargin [5])) ; if (permute) { if (mxGetM (pargin [5]) * mxGetN (pargin [5]) != n || mxIsSparse (pargin [5])) { mexErrMsgTxt ("ldl: invalid input permutation\n") ; } P = (Long *) mxMalloc (nn * sizeof (Long)) ; p = mxGetPr (pargin [5]) ; for (k = 0 ; k < n ; k++) { P [k] = p [k]; /*p[k]-1 convert to 0-based */ } if (mxGetM (pargin [6]) * mxGetN (pargin [6]) != n || mxIsSparse (pargin [6])) { mexErrMsgTxt ("ldl: invalid input permutation inverse\n") ; } Pinv = (Long *) mxMalloc (nn * sizeof (Long)) ; p = mxGetPr (pargin [6]) ; for (k = 0 ; k < n ; k++) { Pinv [k] = p [k]; /*p[k]-1 convert to 0-based */ } } else { P = (Long *) NULL ; Pinv = (Long *) NULL ; } /* get workspace */ Y = (double *) mxMalloc (nn * sizeof (double)) ; Pattern = (Long *) mxMalloc (nn * sizeof (Long)) ; /* make sure the input P is valid */ if (permute && !ldl_l_valid_perm (n, P, Flag)) { mexErrMsgTxt ("ldl: invalid input permutation\n") ; } /* note that we assume that the input matrix is valid */ /* ---------------------------------------------------------------------- */ /* symbolic factorization to get Lp, Parent, Lnz, and optionally Pinv */ /* ---------------------------------------------------------------------- */ /*ldl_l_symbolic (n, Ap, Ai, Lp, Parent, Lnz, Flag, P, Pinv) ;*/ lnz = Lp [n] ; printf ("lnz: %d\n", lnz) ; /* ---------------------------------------------------------------------- */ /* create outputs */ /* ---------------------------------------------------------------------- */ /* create the output matrix L, using the Lp array from ldl_l_symbolic */ pargout [0] = mxCreateSparse (n, n, lnz+1, mxREAL) ; mxFree (mxGetJc (pargout [0])) ; mxSetJc (pargout [0], (void *) Lp) ; /* Lp is not mxFree'd */ Li = (Long *) mxGetIr (pargout [0]) ; Lx = mxGetPr (pargout [0]) ; /* create sparse diagonal matrix D */ if (nargout > 1) { pargout [1] = mxCreateSparse (n, n, nn, mxREAL) ; Dp = (Long *) mxGetJc (pargout [1]) ; Di = (Long *) mxGetIr (pargout [1]) ; for (j = 0 ; j < n ; j++) { Dp [j] = j ; Di [j] = j ; } Dp [n] = n ; D = mxGetPr (pargout [1]) ; } else { D = (double *) mxMalloc (nn * sizeof (double)) ; } /* ---------------------------------------------------------------------- */ /* numeric factorization to get Li, Lx, and D */ /* ---------------------------------------------------------------------- */ /*d=n; printf ("n: %d\n", n) ; printf ("Y: ") ; for (k = 0 ; k < n ; k++) { Y[k]=k; printf ("%f", Y[k]) ; } printf ("Pattern: ") ; for (k = 0 ; k < n ; k++) { Pattern[k]=k; printf ("%d", Pattern[k]) ; } printf ("Lnz: ") ; for (k = 0 ; k < n ; k++) { Lnz[k]=k; printf ("%d", Lnz[k]) ; }*/ d = ldl_l_numeric (n, Ap, Ai, Ax, Lp, Parent, Lnz, Li, Lx, D, Y, Flag, Pattern, P, Pinv) ; printf ("d: %d\n", d) ; /* ---------------------------------------------------------------------- */ /* singular case : truncate the factorization */ /* ---------------------------------------------------------------------- */ if (d != n) { /* D [d] is zero: report error, or clean up */ mexErrMsgTxt ("ldl: zero pivot encountered\n") ; } /* ---------------------------------------------------------------------- */ /* free workspace */ /* ---------------------------------------------------------------------- */ if (nargout < 2) { mxFree (D) ; } if (permute) { mxFree (P) ; mxFree (Pinv) ; } mxFree (Parent) ; mxFree (Y) ; mxFree (Flag) ; mxFree (Pattern) ; mxFree (Lnz) ; }