Ejemplo n.º 1
0
/*mexFunction handles the argument processing*/
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    
double *weight, *epsilon, *trainpats;
long *orderind;
mxLogical *pos, *neg;
unsigned int *seed;
int *scalardims;
int numfeat, numex, numclass;
long *feat;
double *thresh, *conf;
  
 /*check that the appropriate number of arguments have been passed*/
  if (nrhs != 7) 
    mexErrMsgTxt("Weight, pos, neg, sortedix, epsilon, trainpats, seed required.");
  if (nlhs != 3) 
    mexErrMsgTxt("Outputs: feat, threshind, conf");
  
 /*validate the type of pos and neg (they will need to become mxLogical)*/
  if (!mxIsLogical(prhs[1]))
      mexErrMsgTxt("pos is not logical.");
  if (!mxIsLogical(prhs[2]))
      mexErrMsgTxt("neg is not logical.");

  /*collect the arguments*/
  weight = mxGetData(prhs[0]); 
  pos = mxGetLogicals(prhs[1]); 
  neg = mxGetLogicals(prhs[2]);   
  orderind = (long*)mxGetData(prhs[3]);    
  epsilon = mxGetData(prhs[4]);  
  trainpats = mxGetData(prhs[5]);   
  seed = mxGetData(prhs[6]);

  /*determine the dataset dimenions using the weight and sortedix matrices
  (see matrix sizes above - matrix dimensions are M x N)*/
  numclass = mxGetM(prhs[0]);
  numex = mxGetN(prhs[0]);
  numfeat = mxGetN(prhs[3]);

  /*create the output arguments*/
  
  /*feat is an index and will be returned as a 32-bit int
  set up the matrix size for feat*/
  scalardims = mxCalloc(2,sizeof(int));
  scalardims[0] = scalardims[1] = 1;
  plhs[0] = mxCreateNumericArray(2,scalardims,mxINT32_CLASS,mxREAL);
  /*create the thresh and conf output arguments*/
  plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
  plhs[2] = mxCreateDoubleMatrix(numclass,2,mxREAL);
  
  mxFree(scalardims);
  
  feat = (long *)mxGetPr(plhs[0]);
  thresh = (double *)mxGetPr(plhs[1]); 
  conf = mxGetPr(plhs[2]);  
  
  /*place the call the calculation function*/
  dstump(weight, pos, neg, orderind, trainpats, numfeat, numex, numclass, epsilon, feat, thresh, conf, seed);
}
Ejemplo n.º 2
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int dim, i;
    if (nrhs<6)
        mexErrMsgTxt("Number of arguments must be 6!");
    
    // Get input
    const double* T     = static_cast<double*>(mxGetData(prhs[0]));
    const double* omega = static_cast<double*>(mxGetData(prhs[1]));
    const double* m     = static_cast<double*>(mxGetData(prhs[2]));
    const double* X     = static_cast<double*>(mxGetData(prhs[3]));
    bool doDerivative   = (bool) *mxGetLogicals(prhs[4]);
    bool boundary       = (bool) *mxGetLogicals(prhs[5]);
    
    // get dimension, h and number of elements N
    dim = mxGetN(prhs[1]) / 2;
    double h[3]; //h[dim];
    for (i=0; i<dim; i++) {
        h[i] = (omega[2*i+1]-omega[2*i]) / m[i];
    }
    const int N = mxGetM(prhs[3])/dim;
    
    //Allocate Tc
    mwSize dims[2]; dims[0] = N; dims[1] = 1;
    plhs[0] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS, mxREAL);
    double* Tc = static_cast<double*>(mxGetData(plhs[0]));
    
    double* dT = 0;
    //Allocate dT
    if (doDerivative) {
        dims[1] = dim; 
        plhs[1] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS, mxREAL);
        dT = static_cast<double*>(mxGetData(plhs[1]));
    } else {
        dims[0] = 1; dims[1] = 1;
        plhs[1] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS, mxREAL);
        dT = static_cast<double*>(mxGetData(plhs[1]));
    }
    
    switch (dim) {
        case 1:
            splineInter1D(Tc,dT,T,omega,m,N,X,h,doDerivative, boundary);
            break;
        case 2:
            splineInter2D(Tc,dT,T,omega,m,N,X,h,doDerivative, boundary);
            break;
        case 3:
            splineInter3D(Tc,dT,T,omega,m,N,X,h,doDerivative, boundary);
            break;
        default:
            break;
    }
}
Ejemplo n.º 3
0
void mexFunction(int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs) {

    /* Initialize some variables */
    double *appearance, *newCoordsX, *newCoordsY, *size_aam, *warped_appear;
    int i, appear_height, height, width;
    bool *in;
    
    /* Retrieve inputs */
    appearance = mxGetPr(prhs[0]);
    newCoordsX = mxGetPr(prhs[1]);
    newCoordsY = mxGetPr(prhs[2]);
    in = mxGetLogicals(prhs[3]);
    size_aam = mxGetPr(prhs[4]);
    appear_height = mxGetM(prhs[0]);
    height = (int) size_aam[0];
    width  = (int) size_aam[1];
    
    /* Construct output matrix */
    plhs[0] = mxCreateDoubleMatrix(height, width, mxREAL);
    warped_appear = mxGetPr(plhs[0]);
    
    /* Fill result image */
    for(i = 0; i < height * width; i++) {
        if(in[i]) {
            warped_appear[i] = appearance[(int) newCoordsY[i] - 1 + 
                                         ((int) newCoordsX[i] - 1) * appear_height];
        }
    }
}
Ejemplo n.º 4
0
/*
    PsychSetStructArrayBooleanElement()
    
    Note: The variable "index" is zero-indexed.
*/                                    
void PsychSetStructArrayBooleanElement(	char *fieldName,
                                        int index,
                                        boolean state,
                                        PsychGenericScriptType *pStruct)
{
    int fieldNumber, numElements;
    boolean isStruct;
    mxArray *mxFieldValue;
	 char errmsg[256];


    //check for bogus arguments
    numElements=mxGetM(pStruct) *mxGetN(pStruct);
    if(index>=numElements)
        PsychErrorExitMsg(PsychError_internal, "Attempt to set a structure field at an out-of-bounds index");
    fieldNumber=mxGetFieldNumber(pStruct, fieldName);
    if(fieldNumber==-1) {
		  sprintf(errmsg, "Attempt to set a non-existent structure name field: %s", fieldName);
        PsychErrorExitMsg(PsychError_internal, errmsg);
	 }
    isStruct= mxIsStruct(pStruct);
    if(!isStruct)
        PsychErrorExitMsg(PsychError_internal, "Attempt to set a field within a non-existent structure.");
        
    //do stuff
    mxFieldValue=mxCreateLogicalMatrix(1, 1);
    mxGetLogicals(mxFieldValue)[0]= state;
    mxSetField(pStruct, index, fieldName, mxFieldValue); 
    if (PSYCH_LANGUAGE == PSYCH_OCTAVE) mxDestroyArray(mxFieldValue);
    
}
Ejemplo n.º 5
0
void MxArray::fromVector(const std::vector<bool>& v)
{
    p_ = mxCreateLogicalMatrix(1, v.size());
    if (!p_)
        mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
    std::copy(v.begin(), v.end(), mxGetLogicals(p_));
}
Ejemplo n.º 6
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int i, dimLocal, n = 1, nn = 1, mLocal[3];
    if (nrhs<4)
        mexErrMsgTxt("Number of arguments must be 4!");
    
    // Get input
    const double *yc  = static_cast<double*>(mxGetData(prhs[0]));
    const double *m   = static_cast<double*>(mxGetData(prhs[1]));
    const double *dim = static_cast<double*>(mxGetData(prhs[2]));
    bool mode = (bool) *mxGetLogicals(prhs[3]);
    
    dimLocal = (int) dim[0];
    for (i=0; i<dimLocal; i++) {
        mLocal[i] = (int) m[i];
        n  *= mLocal[i];
        nn *= mLocal[i]+1;
    }
    
    mwSize dims[2];
    
    if (mode) {
        dims[0] = nn*dimLocal; dims[1] = 1;
        plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
        double *yOut = static_cast<double*>(mxGetData(plhs[0]));
        
        center2nodal(yOut, yc, mLocal, dimLocal);
    } else {
        dims[0] = n*dimLocal; dims[1] = 1;
        plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
        double *yOut = static_cast<double*>(mxGetData(plhs[0]));
        
        nodal2center(yOut, yc, mLocal, dimLocal);
    }
}
Ejemplo n.º 7
0
void eng_make_SparseLogical(int *ir, int irlen, int *jc, int jclen, short *list, int len, int m, int n) {
    mxArray *var = mxCreateSparseLogicalMatrix(m, n, len);
    std::copy(ir, ir + irlen, mxGetIr(var));
    std::copy(jc, jc + jclen, mxGetJc(var));
    std::copy(list, list+len, mxGetLogicals(var));
    returnHandle(var);
}
Ejemplo n.º 8
0
/* main matab function */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
 
    /* b = fast_inseg( seg, t ) */
    
    /* current t in current seg? start while block until out of seg, then next seg
     * current t before seg start? binsearch for next t in seg, start while block, next seg
     * current t after seg end? go to next seg
     */
    
    double *seg, *t;
    mxLogical *pout;
    
    int s, current_t, idx;
    int nseg, nt;
    
    if (nrhs!=2)
        mexErrMsgIdAndTxt("fast_inseg:invalidArguments", "Expecting two arguments");
    
    if ( mxGetNumberOfDimensions(prhs[0])!=2 || mxGetN(prhs[0])!=2 )
        mexErrMsgIdAndTxt("fast_inseg:invalidArguments", "Invalid segments");
    
    seg = mxGetPr( prhs[0] );
    t = mxGetPr( prhs[1] );
    
    nseg = mxGetM( prhs[0] );
    nt = mxGetNumberOfElements(prhs[1]);
    
    plhs[0] = mxCreateLogicalMatrix( nt, 1 );
    
    if (nseg==0 || nt==0)
        return;
    
    pout = mxGetLogicals( plhs[0] );

    current_t = 0;
    
    for (s=0; s<nseg; s++) {
     
        if ( t[current_t]<seg[s] ) {
            /* binsearch for next t in seg */
             idx = (int) ceil( bsearchi( &(t[current_t]), nt-current_t, seg[s] ) );
             if (idx==-1)
                 break;
             current_t += idx;
        } else if ( t[current_t]>seg[s+nseg] ) {
            continue;
        }
        
        while ( t[current_t]<=seg[s+nseg] && current_t<nt ) {
            pout[current_t] = 1;
            current_t++;
        }
     
        if (current_t>=nt)
            break;
                
    }
    
}
Ejemplo n.º 9
0
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    mxLogical *image, *outImage;
    mwSize w, h;
	
	if (nrhs != 1){
		mexErrMsgIdAndTxt( "MATLAB:borderFill:wrongInputCount",
				"One input (image) expected.");
	}
	
	/* The input must be a logical.*/
	if(!mxIsLogical(prhs[0])){
		mexErrMsgIdAndTxt( "MATLAB:borderFill:inputNotLogical",
				"Input must be a logical.");
	}

    h = mxGetM(prhs[0]);
    w = mxGetN(prhs[0]);
    image = mxGetLogicals(prhs[0]);

    /* Create matrix for the return argument. */
    plhs[0] = mxCreateLogicalMatrix(h, w);
    outImage = mxGetLogicals(plhs[0]);
    
    /* first and last column */
    for (int y = 0; y < h; y++){
        if (!outImage[y]){
            fill(image, h, w, y, 0, image[y], outImage);
        }
        if (!outImage[h * (w - 1) + y]){
            fill(image, h, w, y, w - 1, image[h * (w - 1) + y], outImage);
        }
    }
    
    /* first and last row */
    for (int x = 1; x < w - 1; x++){
        if (!outImage[x * h]){
            fill(image, h, w, 0, x, image[x * h], outImage);
        }
        if (!outImage[x * h + h - 1]){
            fill(image, h, w, h - 1, x, image[x * h + h - 1], outImage);
        }
    }
}
Ejemplo n.º 10
0
void eng_make_Logical(short *list, int len, int *mmDims, int depth) {
    std::vector<mwSize> mbDimsVec(depth);
    std::reverse_copy(mmDims, mmDims+depth, mbDimsVec.begin());
    mwSize *mbDims = &mbDimsVec[0];

    mxArray *var = mxCreateLogicalArray(depth, mbDims);
    std::copy(list, list+len, mxGetLogicals(var));
    returnHandle(var);
}
Ejemplo n.º 11
0
static boolean_T r_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src,
  const emlrtMsgIdentifier *msgId)
{
  boolean_T ret;
  emlrtCheckBuiltInR2012b(sp, msgId, src, "logical", false, 0U, 0);
  ret = *mxGetLogicals(src);
  emlrtDestroyArray(&src);
  return ret;
}
Ejemplo n.º 12
0
bool CMatlabInterface::get_bool()
{
	const mxArray* b=get_arg_increment();
	if (mxIsLogical(b) && mxGetN(b)==1 && mxGetM(b)==1)
		return mxGetLogicals(b)[0];
	else if (mxIsNumeric(b))
		return (mxGetScalar(b)!=0);
	else
		SG_ERROR("Expected Scalar Boolean as argument %d\n", m_rhs_counter);

	return false;
}
Ejemplo n.º 13
0
void mexFunction(int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs) {

    /* Initialize some variables */
    double *z, *tri, *w, *zi, *xi, *max;
    int i, j, no_pixels, no_tri;
    bool *in;
    
    /* Get inputs */
    no_pixels = mxGetM(prhs[1]);
    no_tri = mxGetN(prhs[1]);
    z   = mxGetPr(prhs[0]);
    tri = mxGetPr(prhs[1]);
    w   = mxGetPr(prhs[2]);
    in  = mxGetLogicals(prhs[3]);
    xi  = mxGetPr(prhs[4]);
    max = mxGetPr(prhs[5]);
    
    /* Allocate memory for the output matrix */
    plhs[0] = mxCreateDoubleMatrix(no_pixels, 1, mxREAL);
    zi = mxGetPr(plhs[0]);
    
    /* Compute pixel displacements */
    for(j = 0; j < no_tri; j++) {
        for(i = 0; i < no_pixels; i++) {
            if(in[i]) {
                zi[i] += (z[(int) tri[i + j * no_pixels] - 1] * w[i + j * no_pixels]);
            }
        }
    }
    
    /* Compute where to take pixels from */
    for(i = 0; i < no_pixels; i++) {
        if(in[i]) {
            
            /* Subtract displacements from original coordinates */
            zi[i] = xi[i] - zi[i];
    
            /* Check whether none of the assignments is out of range, and round */
            if(zi[i] < 1.0) {
               zi[i] = 1.0;
            }
            else if(zi[i] > max[0]) {
               zi[i] = max[0];
            }
            else {
                zi[i] = floor(zi[i]+0.5);
            }
            
            /* Excluding the round makes thing a lot faster, but a bit inaccurate */
        }
    }
}
Ejemplo n.º 14
0
int mxIsLogicalScalarTrue(const mxArray *ptr)
{
    if (mxIsLogicalScalar(ptr) == false)
    {
        return 0;
    }

    if (*mxGetLogicals(ptr) == 0)
    {
        return 0;
    }

    return 1;
}
Ejemplo n.º 15
0
int readMxLogicalDataFromBytes(mxArray *mx, mxGramInfo *info, int nBytes) {
    int ii;
    int numel = info->dataM * info->dataN;
    mxLogical *mxData = mxGetLogicals(mx);
    const char *gramData = info->dataBytes;
    
    if (nBytes >= mxGetElementSize(mx)*numel) {
        for(ii=0; ii<numel; ii++) {
            mxData[ii] = (mxLogical)*gramData;
            gramData += info->dataSize;
        }
        return(info->dataSize*numel);
    } else
        return(-1);
}
Ejemplo n.º 16
0
int writeMxLogicalDataToBytes(const mxArray *mx, mxGramInfo *info, int nBytes) {
    int ii;
    int numel = info->dataM * info->dataN;
    mxLogical *mxData = mxGetLogicals(mx);
    char *gramData = info->dataBytes;
    
    if (nBytes >= info->dataSize*numel) {
        for(ii=0; ii<numel; ii++) {
            *((mxLogical*)gramData) = mxData[ii];
            gramData += info->dataSize;
        }
        return(info->dataSize*numel);
    } else
        return(-1);
}
Ejemplo n.º 17
0
fcvimage * mxArray2fcv(const mxArray *img)
{
	int w, h, d, type, dim;
	const int *dims=0;
	int islogical;
    char *ptr;
	fcvimage *ret;
	
    const mxArray *mx_img = img;
	
	type = mex2fcvType(mxGetClassID(mx_img));
	if(type == -1) return NULL;
    dim =  mxGetNumberOfDimensions(mx_img);
    if (dim < 3) {
        w = mxGetM(mx_img);
        h = mxGetN(mx_img);
        d = 1;
    } else if (dim == 3) {
        dims = (int *)mxGetDimensions(mx_img);
        if (dims == 0){
	        fcv_error("mx2fcv","Cant get dimensions.");
	        return NULL;
		}
        w = dims[0];
        h = dims[1];
        d = dims[2];
    } else {
        fcv_error("mx2fcv","Invalid dimensions.");
        return NULL;
    }

    islogical = mxIsLogical(mx_img);

    if (islogical) {
        ptr = (char *)mxGetLogicals(mx_img);
    } else {
        ptr = (char *)mxGetPr(mx_img);
    }
	
    ret = fcv_createimagestructure(w, h, d, type,FCV_RTAG_RLOCAL,islogical,FCV_MATLAB_DEFAULT_RASTER_ARANGE);
    if(ret == 0){
		fcv_error("mx2fcv","cant create image.");
        return NULL;
	}
	ret->imagedata = ptr;
	
	return ret;
}
Ejemplo n.º 18
0
/* ********************************************************** */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
  int mrows, ncols, i, j, jcol;
  double *inputD64;
  unsigned char *inputU8;
  mxLogical *output;

  /* ************* ACCESS MATLAB VARIABLES ************* */
  mrows = mxGetM(prhs[0]);  ncols = mxGetN(prhs[0]);

  /* Create an array to hold the output. */
  plhs[0] = mxCreateLogicalMatrix(mrows, ncols);
  output = mxGetLogicals(plhs[0]);

  /* ********************* COMPUTE ********************* */

  switch (mxGetClassID(prhs[0])) {
    case (mxDOUBLE_CLASS):
      inputD64 = (double *) mxGetPr(prhs[0]);
      for (j = 0; j < ncols; j++) {
	jcol = j*mrows;
	output[0+jcol] = (inputD64[0+jcol] != 0);
	for (i = 1; i < mrows; i++) {
	  output[i+jcol] = inputD64[i+jcol] && !inputD64[(i-1)+jcol];
	}
      }
      break;
    case(mxUINT8_CLASS):
    case(mxLOGICAL_CLASS):
      inputU8 = (unsigned char *) mxGetData(prhs[0]);
      for (j = 0; j < ncols; j++) {
	jcol = j*mrows;
	output[0+jcol] = (inputU8[0+jcol] != 0);
	for (i = 1; i < mrows; i++) {
	  output[i+jcol] = inputU8[i+jcol] && !inputU8[(i-1)+jcol];
	}
      }
      break;
    default:
      mexErrMsgTxt("Invalid Data Type.\n");
  }
  

  /* ********************* CLEAN UP ******************** */

}
Ejemplo n.º 19
0
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
   mexPrintf("Running m3f_tib_sampleOffsets\n");

   omp_set_num_threads(MAX_NUM_THREADS);

   // Extract input information
   const mxArray* data = prhs[0];
   uint32_t* users = (uint32_t*)mxGetData(mxGetField(data, 0, "users"));
   uint32_t* items = (uint32_t*)mxGetData(mxGetField(data, 0, "items"));
   const mxArray* exampsByUser = mxGetField(data, 0, "exampsByUser");
   const mxArray* exampsByItem = mxGetField(data, 0, "exampsByItem");
   const mxArray* model = prhs[1];
   int KU = (*mxGetPr(mxGetField(model, 0, "KU"))) + .5;
   int KM = (*mxGetPr(mxGetField(model, 0, "KM"))) + .5;
   int numUsers = (*mxGetPr(mxGetField(model, 0, "numUsers"))) + .5;
   int numItems = (*mxGetPr(mxGetField(model, 0, "numItems"))) + .5;
   double invSigmaSqd = 1.0/(*mxGetPr(mxGetField(model, 0, "sigmaSqd")));
   double invSigmaSqd0 = 1.0/(*mxGetPr(mxGetField(model, 0, "sigmaSqd0")));
   double c0 = (*mxGetPr(mxGetField(model, 0, "c0")));
   double d0 = (*mxGetPr(mxGetField(model, 0, "d0")));
   const mxArray* samp = prhs[2];
   double* c = mxGetPr(mxGetField(samp, 0, "c")); // KM x numUsers
   double* d = mxGetPr(mxGetField(samp, 0, "d")); // KU x numItems
   uint32_t* zU = (uint32_t*)mxGetData(prhs[3]);
   uint32_t* zM = (uint32_t*)mxGetData(prhs[4]);
   double* resids = mxGetPr(prhs[5]);
   mxLogical* sampParams = NULL;
   if(nrhs > 6){
      sampParams = mxGetLogicals(prhs[6]);
   }

   // Sample c offsets
   if((KM > 0) && ((sampParams == NULL) || sampParams[0])){
      sampleOffsets(users, items, exampsByUser, KU, KM, numUsers,
                    invSigmaSqd, invSigmaSqd0, c0, c, d, zU,
                    zM, resids);
   }

   // Sample d offsets
   if((KU > 0) && ((sampParams == NULL) || sampParams[1])){
      sampleOffsets(items, users, exampsByItem, KM, KU, numItems,
                    invSigmaSqd, invSigmaSqd0, d0, d, c, zM,
                    zU, resids);
   }
}
Ejemplo n.º 20
0
void mexFunction( int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray*prhs[] )
     
{
	double *W = mxGetPr(prhs[0]);
	double *p = mxGetPr(prhs[1]);
	int wm = mxGetM(prhs[0]);
	int wn = mxGetN(prhs[0]);
	int k = mxGetScalar(prhs[2]);
	plhs[0] = mxDuplicateArray(prhs[3]);/* lemasolom a tombot, mert az input parameter const */
	double *x = mxGetPr(plhs[0]);
	bool *freePixels = mxGetLogicals(prhs[4]);
	double *beta = mxGetPr(prhs[5]);
	double *gamma = mxGetPr(prhs[6]);
	int numIters = mxGetScalar(prhs[7]);
	SART(W,wm,wn,p,k,x,freePixels,beta,gamma, numIters);
}
Ejemplo n.º 21
0
void parseGeneralInputs(int nrhs, const mxArray *prhs[], bool *registerTF, TaskHandle *taskID) 
{
	assert(nrhs>=1);
	const mxArray *task = prhs[0];
	TaskHandle *taskIDPtr;

	//Get TaskHandle
	taskIDPtr = (TaskHandle*)mxGetData(mxGetProperty(prhs[0],0, "taskID"));
	*taskID = (TaskHandle)*taskIDPtr;

	//Process argument 2 - registerTF
	if ((nrhs < 2) || mxIsEmpty(prhs[1])) {
		*registerTF =  true;
	} else {
		mxLogical *registerTFTemp = mxGetLogicals(prhs[1]);
		*registerTF = (bool) *registerTFTemp;
	}
}
Ejemplo n.º 22
0
void mexFunction(int nlhs_m, mxArray *plhs_m[], int nrhs_m, const mxArray *prhs_m[])
{
		
	if (nlhs_m > 1)
	{
		printf("Error, only one ouput parameter allowed!\n");
		return;
	}

	if (nrhs_m != 1)
	{
		printf("Error, only one input parameter allowed!\n");
		return;
	}
	
	plhs_m[0] = mxCreateLogicalMatrix(1,1);		
	
	*(mxGetLogicals(plhs_m[0])) = mxIsComplex(prhs_m[0]);

	return;
}
void mexFunction(
    int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
{
  double *phi;
  mxLogical *contour;
  int iWidth, iHeight;
  
  /* The input must be a noncomplex scalar double.*/
  iHeight = mxGetM(prhs[0]);
  iWidth = mxGetN(prhs[0]);

  /* Create matrix for the return argument. */
  plhs[0] = mxCreateLogicalMatrix(iHeight,iWidth);
  
  /* Assign pointers to each input and output. */
  phi = mxGetPr(prhs[0]);
  contour = mxGetLogicals(plhs[0]);

	for (int i = 0; i < iWidth; i++) {
		for (int j = 0; j < iHeight; j++) {
			if (phi[i*iHeight+j] >= 0) {
        			bool bIsNeighbourBelowZero = false;
				for (int k = -1; k <= 1; k++)  {
          				for (int l = -1; l <= 1; l++) {
						if (i+k >= 0 && i+k < iWidth && j+l >= 0 && j+l < iHeight && phi[(i+k)*iHeight+j+l] < 0) {
              						if (-phi[(i+k)*iHeight+j+l] < phi[i*iHeight+j]) {
                						contour[(i+k)*iHeight+j+l] = true;
							}
							else {
								contour[i*iHeight+j] = true;
							}
						}
					}
				}
      			}
    		}
  	}
}
Ejemplo n.º 24
0
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
   mexPrintf("Running sampleTopicParams\n");

   omp_set_num_threads(MAX_NUM_THREADS);

   // Extract input information
   const mxArray* data = prhs[0];
   const mxArray* exampsByUser = mxGetField(data, 0, "exampsByUser");
   const mxArray* exampsByItem = mxGetField(data, 0, "exampsByItem");
   const mxArray* model = prhs[1];
   int KU = (*mxGetPr(mxGetField(model, 0, "KU"))) + .5;
   int KM = (*mxGetPr(mxGetField(model, 0, "KM"))) + .5;
   int numUsers = (*mxGetPr(mxGetField(model, 0, "numUsers"))) + .5;
   int numItems = (*mxGetPr(mxGetField(model, 0, "numItems"))) + .5;
   double alpha = (*mxGetPr(mxGetField(model, 0, "alpha")));
   const mxArray* samp = prhs[2];
   double* logthetaU = mxGetPr(mxGetField(samp, 0, "logthetaU")); // KU x numUsers
   double* logthetaM = mxGetPr(mxGetField(samp, 0, "logthetaM")); // KM x numItems
   uint32_t* zU = (uint32_t*)mxGetData(prhs[3]);
   uint32_t* zM = (uint32_t*)mxGetData(prhs[4]);
   mxLogical* sampParams = NULL;
   if(nrhs > 5){
      sampParams = mxGetLogicals(prhs[5]);
   }

   // Sample user topic parameters
   if((KU > 1) && ((sampParams == NULL) || sampParams[0])){
      sampleTopicParams(exampsByUser, KU, numUsers, alpha, logthetaU, zU);
   }
   // Sample item topic parameters
   if((KM > 1) && ((sampParams == NULL) || sampParams[1])){
      sampleTopicParams(exampsByItem, KM, numItems, alpha, logthetaM, zM);
   }
}
Ejemplo n.º 25
0
/* Gateway function with Matlab */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[]) {
    char *cmd;
    /* If no input argument, print out the usage */
    if (nrhs == 0) {
        mexErrMsgTxt("Usage: messenger('init|listen|respond', extra1, extra2, ...)");
    }

    /* Get the input command */
    if(!(cmd = mxArrayToString(prhs[0]))) {
        mexErrMsgTxt("Cannot read the command");
    }

    /* Initialize a new server session */
    if (strcmp(cmd, "init") == 0) {
        char *socket_addr;
        mxLogical *p;

        /* Check if the input format is valid */
        if (nrhs != 2) {
            mexErrMsgTxt("Missing argument: socket address");
        }
        if (!(socket_addr = mxArrayToString(prhs[1]))) {
            mexErrMsgTxt("Cannot read socket address");
        }

        plhs[0] = mxCreateLogicalMatrix(1, 1);
        p = mxGetLogicals(plhs[0]);

        if (!initialized) {
            if (!initialize(socket_addr)) {
                p[0] = 1;
                mexPrintf("Socket created at: %s\n", socket_addr);
            } else {
                p[0] = 0;
                mexErrMsgTxt("Socket creation failed.");
            }
        } else {
            mexErrMsgTxt("One socket has already been initialized.");
        }

        return;

    /* Listen over an existing socket */
    } else if (strcmp(cmd, "listen") == 0) {
        char *recv_buffer = mxCalloc(BUFLEN, sizeof(char));

        int byte_recvd = listen_zmq(recv_buffer, BUFLEN);

        while (byte_recvd == -1 && errno == EAGAIN) {
        	mexCallMATLAB(0, NULL, 0, NULL, "drawnow");
        	byte_recvd = listen_zmq(recv_buffer, BUFLEN);
       	}

        /* Check if the received data is complete and correct */
        if ((byte_recvd > -1) && (byte_recvd <= BUFLEN)) {
            plhs[0] = mxCreateString(recv_buffer);
        } else if (byte_recvd > BUFLEN){
            mexErrMsgTxt("Receiver buffer overflow. Message truncated");
        } else {
        	sprintf(recv_buffer, "Failed to receive a message due to ZMQ error %s", strerror(errno));
            mexErrMsgTxt(recv_buffer);
        }

        return;

    /* Send a message out */
    } else if (strcmp(cmd, "respond") == 0) {
        size_t msglen;
        char *msg_out;
        mxLogical *p;

        /* Check if the input format is valid */
        if (nrhs != 2) {
            mexErrMsgTxt("Please provide the message to send");
        }

        msglen = mxGetNumberOfElements(prhs[1]);
        msg_out = mxArrayToString(prhs[1]);

        plhs[0] = mxCreateLogicalMatrix(1, 1);
        p = mxGetLogicals(plhs[0]);

        if (msglen == respond(msg_out, msglen)) {
            p[0] = 1;
        } else {
            p[0] = 0;
            mexErrMsgTxt("Failed to send message due to ZMQ error");
        }

        return;

    /* Close the socket and context */
    } else if (strcmp(cmd, "exit") == 0) {
        cleanup();

        return;
    } else {
        mexErrMsgTxt("Unidentified command");
    }
}
Ejemplo n.º 26
0
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum {IN_I = 0, IN_END} ;
  enum {OUT_FRAMES=0, OUT_DESCRIPTORS, OUT_INFO, OUT_END} ;

  int verbose = 0 ;
  int opt ;
  int next = IN_END ;
  mxArray const *optarg ;
  VlEnumerator *pair ;

  float const *image ;
  vl_size numCols, numRows ;

  VlCovDetMethod method = VL_COVDET_METHOD_DOG;
  vl_bool estimateAffineShape = VL_FALSE ;
  vl_bool estimateOrientation = VL_FALSE ;

  vl_bool doubleImage = VL_TRUE ;
  vl_index octaveResolution = -1 ;
  double edgeThreshold = -1 ;
  double peakThreshold = -1 ;
  double lapPeakThreshold = -1 ;

  int descriptorType = -1 ;
  vl_index patchResolution = -1 ;
  double patchRelativeExtent = -1 ;
  double patchRelativeSmoothing = -1 ;
  float *patch = NULL ;
  float *patchXY = NULL ;

  vl_int liopNumSpatialBins = 6;
  vl_int liopNumNeighbours = 4;
  float liopRadius = 6.0;
  float liopIntensityThreshold = VL_NAN_F ;

  double boundaryMargin = 2.0 ;

  double * userFrames = NULL ;
  vl_size userFrameDimension = 0 ;
  vl_size numUserFrames = 0 ;

  VL_USE_MATLAB_ENV ;

  /* -----------------------------------------------------------------
   *                                               Check the arguments
   * -------------------------------------------------------------- */

  if (nin < IN_END) {
    vlmxError(vlmxErrNotEnoughInputArguments, 0) ;
  } else if (nout > OUT_END) {
    vlmxError(vlmxErrTooManyOutputArguments, 0) ;
  }

  if (mxGetNumberOfDimensions(IN(I)) != 2 ||
      mxGetClassID(IN(I)) != mxSINGLE_CLASS){
    vlmxError(vlmxErrInvalidArgument, "I must be a matrix of class SINGLE.") ;
  }

  image = (float*) mxGetData(IN(I)) ;
  numRows = mxGetM(IN(I)) ;
  numCols = mxGetN(IN(I)) ;

  while ((opt = vlmxNextOption (in, nin, options, &next, &optarg)) >= 0) {

    switch (opt) {

    case opt_verbose :
      ++ verbose ;
      break ;

    case opt_method:
      pair = vlmxDecodeEnumeration(optarg, vlCovdetMethods, VL_TRUE) ;
      if (pair == NULL) {
        vlmxError(vlmxErrInvalidArgument, "METHOD is not a supported detection method.") ;
      }
      method = (VlCovDetMethod)pair->value ;
      break;

      case opt_descriptor:
        pair = vlmxDecodeEnumeration(optarg, vlCovDetDescriptorTypes, VL_TRUE) ;
        if (pair == NULL) {
          vlmxError(vlmxErrInvalidArgument, "DESCRIPTOR is not a supported descriptor.") ;
        }
        descriptorType = (VlCovDetDescriptorType)pair->value ;
        break;

    case opt_estimate_affine_shape:
      if (!mxIsLogicalScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "ESTIMATEAFFINESHAPE must be a logical scalar value.") ;
      } else {
        estimateAffineShape = *mxGetLogicals(optarg) ;
      }
      break ;

    case opt_estimate_orientation:
      if (!mxIsLogicalScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "ESTIMATEORIENTATION must be a logical scalar value.") ;
      } else {
        estimateOrientation = *mxGetLogicals(optarg);
      }
      break ;

    case opt_double_image:
      if (!mxIsLogicalScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "DOUBLEIMAGE must be a logical scalar value.") ;
      } else {
        doubleImage = *mxGetLogicals(optarg);
      }
      break ;

    case opt_octave_resolution :
      if (!vlmxIsPlainScalar(optarg) || (octaveResolution = (vl_index)*mxGetPr(optarg)) < 1) {
        vlmxError(vlmxErrInvalidArgument, "OCTAVERESOLUTION must be an integer not smaller than 1.") ;
      }
      break ;

    case opt_edge_threshold :
      if (!vlmxIsPlainScalar(optarg) || (edgeThreshold = *mxGetPr(optarg)) < 1) {
        vlmxError(vlmxErrInvalidArgument, "EDGETHRESHOLD must be a real not smaller than 1.") ;
      }
      break ;

    case opt_peak_threshold :
      if (!vlmxIsPlainScalar(optarg) || (peakThreshold = *mxGetPr(optarg)) < 0) {
        vlmxError(vlmxErrInvalidArgument, "PEAKTHRESHOLD must be a non-negative real.") ;
      }
      break ;
        
    case opt_laplacian_peak_threshold :
      if (!vlmxIsPlainScalar(optarg) || (lapPeakThreshold = *mxGetPr(optarg)) < 0) {
        vlmxError(vlmxErrInvalidArgument, "LAPLACIANPEAKTHRESHOLD must be a non-negative real.") ;
      }
      break ;

    case opt_patch_relative_smoothing :
      if (!vlmxIsPlainScalar(optarg) || (patchRelativeSmoothing = *mxGetPr(optarg)) < 0) {
        vlmxError(vlmxErrInvalidArgument, "PATCHRELATIVESMOOTHING must be a non-negative real.") ;
      }
      break ;

    case opt_patch_relative_extent :
      if (!vlmxIsPlainScalar(optarg) || (patchRelativeExtent = *mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "PATCHRELATIVEEXTENT must be a posiive real.") ;
      }
      break ;

    case opt_patch_resolution :
      if (!vlmxIsPlainScalar(optarg) || (patchResolution = (vl_index)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "PATCHRESOLUTION must be a positive integer.") ;
      }
      break ;

    case opt_liop_bins :
      if (!vlmxIsPlainScalar(optarg) || (liopNumSpatialBins = (vl_int)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "number of LIOPNUMSPATIALBINS is not a positive scalar.") ;
      }
      break ;

    case opt_liop_neighbours :
      if (!vlmxIsPlainScalar(optarg) || (liopNumNeighbours = (vl_int)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "number of LIOPNUMNEIGHBOURS is not a positive scalar.") ;
      }
      break ;

    case opt_liop_radius :
      if (!vlmxIsPlainScalar(optarg) || (liopRadius = (float)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "LIOPRADIUS must is not a positive scalar.") ;
      }
      break ;

    case opt_liop_threshold :
      if (!vlmxIsPlainScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "LIOPINTENSITYTHRESHOLD is not a scalar.") ;
      }
      liopIntensityThreshold = *mxGetPr(optarg) ;
      break ;

    case opt_frames:
      if (!vlmxIsPlainMatrix(optarg,-1,-1)) {
        vlmxError(vlmxErrInvalidArgument, "FRAMES must be a palin matrix.") ;
      }
      numUserFrames = mxGetN (optarg) ;
      userFrameDimension = mxGetM (optarg) ;
      userFrames = mxGetPr (optarg) ;
      switch (userFrameDimension) {
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
            /* ok */
          break ;
        default:
          vlmxError(vlmxErrInvalidArgument,
                    "FRAMES of dimensions %d are not recognised",
                    userFrameDimension); ;
      }
      break ;

    default :
      abort() ;
    }
  }

  if (descriptorType < 0) descriptorType = VL_COVDET_DESC_SIFT ;

  switch (descriptorType) {
    case VL_COVDET_DESC_NONE :
      break ;

    case VL_COVDET_DESC_PATCH :
      if (patchResolution < 0)  patchResolution = 20 ;
      if (patchRelativeExtent < 0) patchRelativeExtent = 6 ;
      if (patchRelativeSmoothing < 0) patchRelativeSmoothing = 1 ;
      break ;

    case VL_COVDET_DESC_SIFT :
      /* the patch parameters are selected to match the SIFT descriptor geometry */
      if (patchResolution < 0)  patchResolution = 15 ;
      if (patchRelativeExtent < 0) patchRelativeExtent = 7.5 ;
      if (patchRelativeSmoothing < 0) patchRelativeSmoothing = 1 ;
      break ;

    case VL_COVDET_DESC_LIOP :
      if (patchResolution < 0)  patchResolution = 20 ;
      if (patchRelativeExtent < 0) patchRelativeExtent = 4 ;
      if (patchRelativeSmoothing < 0) patchRelativeSmoothing = 0.5 ;
      break ;
  }

  if (patchResolution > 0) {
    vl_size w = 2*patchResolution + 1 ;
    patch = mxMalloc(sizeof(float) * w * w);
    patchXY = mxMalloc(2 * sizeof(float) * w * w);
  }

  if (descriptorType == VL_COVDET_DESC_LIOP && liopRadius > patchResolution) {
    vlmxError(vlmxErrInconsistentData, "LIOPRADIUS is larger than PATCHRESOLUTION.") ;
  }

  /* -----------------------------------------------------------------
   *                                                          Detector
   * -------------------------------------------------------------- */
  {
    VlCovDet * covdet = vl_covdet_new(method) ;

    /* set covdet parameters */
    vl_covdet_set_transposed(covdet, VL_TRUE) ;
    vl_covdet_set_first_octave(covdet, doubleImage ? -1 : 0) ;
    if (octaveResolution >= 0) vl_covdet_set_octave_resolution(covdet, octaveResolution) ;
    if (peakThreshold >= 0) vl_covdet_set_peak_threshold(covdet, peakThreshold) ;
    if (edgeThreshold >= 0) vl_covdet_set_edge_threshold(covdet, edgeThreshold) ;
    if (lapPeakThreshold >= 0) vl_covdet_set_laplacian_peak_threshold(covdet, lapPeakThreshold) ;
    
    if (verbose) {
      VL_PRINTF("vl_covdet: doubling image: %s\n",
                VL_YESNO(vl_covdet_get_first_octave(covdet) < 0)) ;
    }

    /* process the image */
    vl_covdet_put_image(covdet, image, numRows, numCols) ;

    /* fill with frames: eitehr run the detector of poure them in */
    if (numUserFrames > 0) {
      vl_index k ;

      if (verbose) {
        mexPrintf("vl_covdet: sourcing %d frames\n", numUserFrames) ;
      }

      for (k = 0 ; k < (signed)numUserFrames ; ++k) {
        double const * uframe = userFrames + userFrameDimension * k ;
        double a11, a21, a12, a22 ;
        VlCovDetFeature feature ;
        feature.peakScore = VL_INFINITY_F ;
        feature.edgeScore = 1.0 ;
        feature.frame.x = (float)uframe[1] - 1 ;
        feature.frame.y = (float)uframe[0] - 1 ;

        switch (userFrameDimension) {
          case 2:
            a11 = 1.0 ;
            a21 = 0.0 ;
            a12 = 0.0 ;
            a22 = 1.0 ;
            break ;
          case 3:
            a11 = uframe[2] ;
            a21 = 0.0 ;
            a12 = 0.0 ;
            a22 = uframe[2] ;
            break ;
          case 4:
          {
            double sigma = uframe[2] ;
            double c = cos(uframe[3]) ;
            double s = sin(uframe[3]) ;
            a11 = sigma * c ;
            a21 = sigma * s ;
            a12 = sigma * (-s) ;
            a22 = sigma * c ;
            break ;
          }
          case 5:
          {
            double d2 ;
            if (uframe[2] < 0) {
              vlmxError(vlmxErrInvalidArgument, "FRAMES(:,%d) does not have a PSD covariance.", k+1) ;
            }
            a11 = sqrt(uframe[2]) ;
            a21 = uframe[3] / VL_MAX(a11, 1e-10) ;
            a12 = 0.0 ;
            d2 = uframe[4] - a21*a21 ;
            if (d2 < 0) {
              vlmxError(vlmxErrInvalidArgument, "FRAMES(:,%d) does not have a PSD covariance.", k+1) ;
            }
            a22 = sqrt(d2) ;
            break ;
          }
          case 6:
          {
            a11 = uframe[2] ;
            a21 = uframe[3] ;
            a12 = uframe[4] ;
            a22 = uframe[5] ;
            break ;
          }
          default:
            a11 = 0 ;
            a21 = 0 ;
            a12 = 0 ;
            a22 = 0 ;
            assert(0) ;
        }
        feature.frame.a11 = (float)a22 ;
        feature.frame.a21 = (float)a12 ;
        feature.frame.a12 = (float)a21 ;
        feature.frame.a22 = (float)a11 ;
        vl_covdet_append_feature(covdet, &feature) ;
      }
    } else {
      if (verbose) {
        mexPrintf("vl_covdet: detector: %s\n",
                  vl_enumeration_get_by_value(vlCovdetMethods, method)->name) ;
        mexPrintf("vl_covdet: peak threshold: %g, edge threshold: %g\n",
                  vl_covdet_get_peak_threshold(covdet),
                  vl_covdet_get_edge_threshold(covdet)) ;
      }

      vl_covdet_detect(covdet) ;

      if (verbose) {
        vl_index i ;
        vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
        mexPrintf("vl_covdet: %d features suppressed as duplicate (threshold: %g)\n",
                  vl_covdet_get_num_non_extrema_suppressed(covdet),
                  vl_covdet_get_non_extrema_suppression_threshold(covdet)) ;
        switch (method) {
        case VL_COVDET_METHOD_HARRIS_LAPLACE:
        case VL_COVDET_METHOD_HESSIAN_LAPLACE:
          {
            vl_size numScales ;
            vl_size const * numFeaturesPerScale ;
            numFeaturesPerScale = vl_covdet_get_laplacian_scales_statistics
              (covdet, &numScales) ;
            mexPrintf("vl_covdet: Laplacian scales:") ;
            for (i = 0 ; i <= (signed)numScales ; ++i) {
              mexPrintf("%d with %d scales;", numFeaturesPerScale[i], i) ;
            }
            mexPrintf("\n") ;
          }
          break ;
        default:
          break ;
        }
        mexPrintf("vl_covdet: detected %d features\n", numFeatures) ;
      }

      if (boundaryMargin > 0) {
        vl_covdet_drop_features_outside (covdet, boundaryMargin) ;
        if (verbose) {
          vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
          mexPrintf("vl_covdet: kept %d inside the boundary margin (%g)\n",
                    numFeatures, boundaryMargin) ;
        }
      }
    }

    /* affine adaptation if needed */
    if (estimateAffineShape) {
      if (verbose) {
        vl_size numFeaturesBefore = vl_covdet_get_num_features(covdet) ;
        mexPrintf("vl_covdet: estimating affine shape for %d features\n", numFeaturesBefore) ;
      }

      vl_covdet_extract_affine_shape(covdet) ;

      if (verbose) {
        vl_size numFeaturesAfter = vl_covdet_get_num_features(covdet) ;
        mexPrintf("vl_covdet: %d features passed affine adaptation\n", numFeaturesAfter) ;
      }
    }

    /* orientation estimation if needed */
    if (estimateOrientation) {
      vl_size numFeaturesBefore = vl_covdet_get_num_features(covdet) ;
      vl_size numFeaturesAfter ;

      vl_covdet_extract_orientations(covdet) ;

      numFeaturesAfter = vl_covdet_get_num_features(covdet) ;
      if (verbose && numFeaturesAfter > numFeaturesBefore) {
        mexPrintf("vl_covdet: %d duplicate features were crated due to ambiguous "
                  "orientation detection (%d total)\n",
                  numFeaturesAfter - numFeaturesBefore, numFeaturesAfter) ;
      }
    }

    /* store results back */
    {
      vl_index i  ;
      vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
      VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
      double * pt ;

      OUT(FRAMES) = mxCreateDoubleMatrix (6, numFeatures, mxREAL) ;
      pt = mxGetPr(OUT(FRAMES)) ;

      for (i = 0 ; i < (signed)numFeatures ; ++i) {
        /* save the transposed frame, adjust origin to MATLAB's*/
        *pt++ = feature[i].frame.y + 1 ;
        *pt++ = feature[i].frame.x + 1 ;
        *pt++ = feature[i].frame.a22 ;
        *pt++ = feature[i].frame.a12 ;
        *pt++ = feature[i].frame.a21 ;
        *pt++ = feature[i].frame.a11 ;
      }
    }

    if (nout >= 2) {
      switch (descriptorType) {
        case VL_COVDET_DESC_NONE:
          OUT(DESCRIPTORS) = mxCreateDoubleMatrix(0,0,mxREAL);
          break ;

        case VL_COVDET_DESC_PATCH:
        {
		  vl_size numFeatures ;
		  VlCovDetFeature const * feature ;
          vl_index i ;
          vl_size w = 2*patchResolution + 1 ;
          float * desc ;

          if (verbose) {
            mexPrintf("vl_covdet: descriptors: type=patch, "
                      "resolution=%d, extent=%g, smoothing=%g\n",
                      patchResolution, patchRelativeExtent,
                      patchRelativeSmoothing);
          }
          numFeatures = vl_covdet_get_num_features(covdet) ;
          feature = vl_covdet_get_features(covdet);
          OUT(DESCRIPTORS) = mxCreateNumericMatrix(w*w, numFeatures, mxSINGLE_CLASS, mxREAL) ;
          desc = mxGetData(OUT(DESCRIPTORS)) ;
          for (i = 0 ; i < (signed)numFeatures ; ++i) {
            vl_covdet_extract_patch_for_frame(covdet,
                                    desc,
                                    patchResolution,
                                    patchRelativeExtent,
                                    patchRelativeSmoothing,
                                    feature[i].frame) ;
            desc += w*w ;
          }
          break ;
        }
        case VL_COVDET_DESC_SIFT:
        {
          vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
          VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
          VlSiftFilt * sift = vl_sift_new(16, 16, 1, 3, 0) ;
          vl_index i ;
          vl_size dimension = 128 ;
          vl_size patchSide = 2 * patchResolution + 1 ;
          double patchStep = (double)patchRelativeExtent / patchResolution ;
          float tempDesc [128] ;
          float * desc ;
          if (verbose) {
            mexPrintf("vl_covdet: descriptors: type=sift, "
                      "resolution=%d, extent=%g, smoothing=%g\n",
                      patchResolution, patchRelativeExtent,
                      patchRelativeSmoothing);
          }
          OUT(DESCRIPTORS) = mxCreateNumericMatrix(dimension, numFeatures, mxSINGLE_CLASS, mxREAL) ;
          desc = mxGetData(OUT(DESCRIPTORS)) ;
          vl_sift_set_magnif(sift, 3.0) ;
          for (i = 0 ; i < (signed)numFeatures ; ++i) {
            vl_covdet_extract_patch_for_frame(covdet,
                                              patch,
                                              patchResolution,
                                              patchRelativeExtent,
                                              patchRelativeSmoothing,
                                              feature[i].frame) ;

            vl_imgradient_polar_f (patchXY, patchXY +1,
                                   2, 2 * patchSide,
                                   patch, patchSide, patchSide, patchSide) ;


            /*
             Note: the patch is transposed, so that x and y are swapped.
             However, if NBO is not divisible by 4, then the configuration
             of the SIFT orientations is not symmetric by rotations of pi/2.
             Hence the only option is to rotate the descriptor further by
             an angle we need to compute the descriptor rotaed by an additional pi/2
             angle. In this manner, x concides and y is flipped.
             */
            vl_sift_calc_raw_descriptor (sift,
                                         patchXY,
                                         tempDesc,
                                         (int)patchSide, (int)patchSide,
                                         (double)(patchSide-1) / 2, (double)(patchSide-1) / 2,
                                         (double)patchRelativeExtent / (3.0 * (4 + 1) / 2) /
                                         patchStep,
                                         VL_PI / 2) ;

            flip_descriptor (desc, tempDesc) ;
            desc += dimension ;
          }
          vl_sift_delete(sift) ;
          break ;
        }
        case VL_COVDET_DESC_LIOP :
        {          /* TODO: get parameters form input */
          vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
          vl_size dimension ;
          VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
          vl_index i ;

          vl_size patchSide = 2 * patchResolution + 1 ;
          float * desc ;

          VlLiopDesc * liop = vl_liopdesc_new(liopNumNeighbours, liopNumSpatialBins, liopRadius, (vl_size)patchSide) ;
          if (!vl_is_nan_f(liopIntensityThreshold)) {
            vl_liopdesc_set_intensity_threshold(liop, liopIntensityThreshold) ;
          }
          dimension = vl_liopdesc_get_dimension(liop) ;
          if (verbose) {
            mexPrintf("vl_covdet: descriptors: type=liop, "
                      "resolution=%d, extent=%g, smoothing=%g\n",
                      patchResolution, patchRelativeExtent,
                      patchRelativeSmoothing);
          }
          OUT(DESCRIPTORS) = mxCreateNumericMatrix(dimension, numFeatures, mxSINGLE_CLASS, mxREAL);
          desc = mxGetData(OUT(DESCRIPTORS)) ;
          vl_tic();
          for(i = 0; i < (signed)numFeatures; i++){
              vl_covdet_extract_patch_for_frame(covdet,
                                                patch,
                                                patchResolution,
                                                patchRelativeExtent,
                                                patchRelativeSmoothing,
                                                feature[i].frame);

              vl_liopdesc_process(liop, desc, patch);

              desc += dimension;

          }
          mexPrintf("time: %f\n",vl_toc());
          mexPrintf("threshold: %f\n",liop->intensityThreshold);
          break;
        }

        default:
          assert(0) ; /* descriptor type */
      }
    }

    if (nout >= 3) {
      vl_index i ;
      vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
      VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
      const char* names[] = {
        "gss",
        "css",
        "peakScores",
        "edgeScores",
        "orientationScore",
        "laplacianScaleScore"
      };
      mxArray * gss_array = _createArrayFromScaleSpace(vl_covdet_get_gss(covdet)) ;
      mxArray * css_array = _createArrayFromScaleSpace(vl_covdet_get_css(covdet)) ;
      mxArray * peak_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;
      mxArray * edge_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;
      mxArray * orientation_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;
      mxArray * laplacian_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;

      float * peak = mxGetData(peak_array) ;
      float * edge = mxGetData(edge_array) ;
      float * orientation = mxGetData(orientation_array) ;
      float * laplacian = mxGetData(laplacian_array) ;
      for (i = 0 ; i < (signed)numFeatures ; ++i) {
        peak[i] = feature[i].peakScore ;
        edge[i] = feature[i].edgeScore ;
        orientation[i] = feature[i].orientationScore ;
        laplacian[i] = feature[i].laplacianScaleScore ;
      }

      OUT(INFO) = mxCreateStructMatrix(1, 1, 6, names) ;
      mxSetFieldByNumber(OUT(INFO), 0, 0, gss_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 1, css_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 2, peak_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 3, edge_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 4, orientation_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 5, laplacian_array) ;
    }
    /* cleanup */
    vl_covdet_delete (covdet) ;
  }

  if (patchXY) mxFree(patchXY) ;
  if (patch) mxFree(patch) ;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    bool				isError;
    thread_policy_flavor_t		flavorConstant;
    int					flavorPolicySize, flavorPolicySizeBytes, kernError;
    task_t				threadID;
    thread_policy_t			threadPolicy;
    mach_msg_type_number_t		policySizeFilled;
    boolean_t				isDefault, getDefault;
    char				commandString[COMMAND_STRING_LENGTH];
    // for return structure
    //  ...outer
    const char *outerNames[] = 		{"threadID", "flavor", "policy", "policySize", "policyFillSize", "getDefault", "isDefault"};
    int	numOuterDims=2, numOuterFields=7;
    int	outerDims[2]={1,1};
    //	...inner
    const char *standardNames[] = 	{"no_data"};
    int numInnerFieldsStandard=		1;
    /*
    const char *extendedNames[] = 	{"timeshare"};
    int numInnerFieldsExtended=		1;
    */
    const char *timeConstraintNames[]=	{"period", "computation", "constraint", "preemptible"};
    int numInnerFieldsTimeConstraint=	4;
    const char *precedenceNames[]=	{"imporantance"};
    int numInnerFieldsPrecedence=	1;
    int	numInnerDims=2;
    int	innerDims[2]={1,1};
    // ...both
    mxArray  *tempFieldValue, *innerStruct, *outerStruct;
    

    

    //get the policy flavor constant specified by the user and the getDefault argument
    if(nrhs<2 || nrhs > 2)
        mexErrMsgTxt("MachGetPriorityMex requires two input arguments.  See help MachGetPriorityMex.");
    if(!mxIsChar(prhs[0]))
        mexErrMsgTxt("First input argument is not a string.  See help MachGetPriorityMex.");
    mxGetString(prhs[0], commandString, COMMAND_STRING_LENGTH);
    isError=GetFlavorConstantFromFlavorString(commandString, mxGetM(prhs[0]) * mxGetN(prhs[0]), &flavorConstant);  //case sensitive.  
    if(isError)
        mexErrMsgTxt("Unrecognized command.  See help MachGetPriorityMex.");
    if(!(mxIsDouble(prhs[1]) || mxIsLogical(prhs[1])) || mxGetN(prhs[1]) * mxGetM(prhs[1]) != 1)
        mexErrMsgTxt("Second argument must be 1x1 logical or double value.  See help MachGetPriorityMex.");
    if(mxIsLogical(prhs[1]))
        getDefault= (boolean_t)mxGetLogicals(prhs[1])[0];
    if(mxIsDouble(prhs[1]))
        getDefault= (boolean_t)mxGetPr(prhs[1])[0];


    //read the priority settings
    switch(flavorConstant){
        case THREAD_STANDARD_POLICY: 
            flavorPolicySizeBytes=sizeof(thread_standard_policy_data_t); 
            flavorPolicySize=THREAD_STANDARD_POLICY_COUNT; 
            break;
        case THREAD_TIME_CONSTRAINT_POLICY: 
            flavorPolicySizeBytes=sizeof(thread_time_constraint_policy_data_t); 
            flavorPolicySize=THREAD_TIME_CONSTRAINT_POLICY_COUNT; 
            break;
        case THREAD_PRECEDENCE_POLICY: 
            flavorPolicySizeBytes=sizeof(thread_precedence_policy_data_t); 
            flavorPolicySize=THREAD_PRECEDENCE_POLICY_COUNT; 
            break;
    }
    threadPolicy=(thread_policy_t)malloc(flavorPolicySizeBytes);		
    threadID= mach_thread_self();
    policySizeFilled=flavorPolicySize;
    isDefault=getDefault;
    kernError=thread_policy_get(threadID, flavorConstant, threadPolicy, &policySizeFilled, &isDefault);

    //create and populate the return structure
    outerStruct= mxCreateStructArray(numOuterDims, outerDims, numOuterFields, outerNames);
    
    tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
    mxGetPr(tempFieldValue)[0]=(double)threadID;
    mxSetField(outerStruct, 0, "threadID", tempFieldValue);
    
    tempFieldValue= mxCreateString(commandString);
    mxSetField(outerStruct, 0, "flavor", tempFieldValue);
    
    
    switch(flavorConstant){
        case THREAD_STANDARD_POLICY: 				
            innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsStandard, standardNames);
            tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
            mxGetPr(tempFieldValue)[0]= (double)((thread_standard_policy_t)threadPolicy)->no_data;
            mxSetField(innerStruct, 0, "no_data", tempFieldValue);
            break;
       /* THREAD_EXTENDED_POLICY is equal to THREAD_STANDARD_POLICY.  Also,  THREAD_EXTENDED_POLICY is undocumented.  So we ignore it.  
        case THREAD_EXTENDED_POLICY: 		
            innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsExtended, extendedNames);
            tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
            mxGetPr(tempFieldValue)[0]= (double)((thread_extended_policy_t)threadPolicy)->timeshare;
            mxSetField(innerStruct, 1, "timeshare", tempFieldValue);
            break;
        */
        case THREAD_TIME_CONSTRAINT_POLICY: 	
            innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsTimeConstraint, timeConstraintNames);
            tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
            mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->period;
            mxSetField(innerStruct, 0, "period", tempFieldValue);
            tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
            mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->computation;
            mxSetField(innerStruct, 0, "computation", tempFieldValue);
            tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
            mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->constraint;
            mxSetField(innerStruct, 0, "constraint", tempFieldValue);
            tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
            mxGetPr(tempFieldValue)[0]= (double)((thread_time_constraint_policy_t)threadPolicy)->preemptible;
            mxSetField(innerStruct, 0, "preemptible", tempFieldValue);
            break;
        case THREAD_PRECEDENCE_POLICY:
            innerStruct= mxCreateStructArray(numInnerDims, innerDims, numInnerFieldsPrecedence, precedenceNames);
            tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
            mxGetPr(tempFieldValue)[0]= (double)((thread_precedence_policy_t)threadPolicy)->importance;
            mxSetField(innerStruct, 0, "imporantance", tempFieldValue);
            break;
    }
    mxSetField(outerStruct,0, "policy", innerStruct);
    
    tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
    mxGetPr(tempFieldValue)[0]=flavorPolicySize;
    mxSetField(outerStruct, 0, "policySize", tempFieldValue);
    
    tempFieldValue= mxCreateDoubleMatrix(1,1,mxREAL);
    mxGetPr(tempFieldValue)[0]=policySizeFilled;
    mxSetField(outerStruct, 0, "policyFillSize", tempFieldValue);
    
    tempFieldValue= mxCreateLogicalMatrix(1, 1);
    mxGetLogicals(tempFieldValue)[0]=(bool)getDefault;
    mxSetField(outerStruct, 0, "getDefault", tempFieldValue);
    
    tempFieldValue= mxCreateLogicalMatrix(1, 1);
    mxGetLogicals(tempFieldValue)[0]=(bool)isDefault;
    mxSetField(outerStruct, 0, "isDefault", tempFieldValue);
    
    plhs[0]=outerStruct;
    
    free((void*)threadPolicy);        
}
Ejemplo n.º 28
0
/** the gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    /* [t, b] = ddm_rand_full(mu, sig2, b_lo, b_up, 
                              delta_t, n[, inv_leak[, seed]]) */

    /* Check argument number */
    if (nlhs != 2) {
        mexErrMsgIdAndTxt("ddm_rand_full:WrongOutputs", 
                          "Wrong number of output arguments");
    }
    if (nrhs < 6) {
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInputs",
                          "Too few input arguments");
    }

    /* Process first 8 arguments */
    if (!MEX_ARGIN_IS_REAL_VECTOR(0))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "First input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(1))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Second input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(2))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Third input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(3))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Fourth input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(4))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Fifth input argument expected to be a double");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(5))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Sixth input argument expected to be a double");
    if (nrhs >= 7 && !MEX_ARGIN_IS_REAL_DOUBLE(6))
        mexErrMsgIdAndTxt("ddm_rand_sym:WrongInput",
                          "Seventh input argument expected to be a double");
    if (nrhs >= 8 && !MEX_ARGIN_IS_REAL_DOUBLE(7))
        mexErrMsgIdAndTxt("ddm_rand_sym:WrongInput",
                          "Eighth input argument expected to be a double");
    int mu_size = std::max(mxGetN(prhs[0]), mxGetM(prhs[0]));
    int sig2_size = std::max(mxGetN(prhs[1]), mxGetM(prhs[1]));
    int b_lo_size = std::max(mxGetN(prhs[2]), mxGetM(prhs[2]));
    int b_up_size = std::max(mxGetN(prhs[3]), mxGetM(prhs[3]));
    ExtArray mu(ExtArray::shared_noowner(mxGetPr(prhs[0])), mu_size);
    ExtArray sig2(ExtArray::shared_noowner(mxGetPr(prhs[1])), sig2_size);
    ExtArray b_lo(ExtArray::shared_noowner(mxGetPr(prhs[2])), b_lo_size);
    ExtArray b_up(ExtArray::shared_noowner(mxGetPr(prhs[3])), b_up_size);
    ExtArray b_lo_deriv = ExtArray::const_array(0.0);
    ExtArray b_up_deriv = ExtArray::const_array(0.0);
    double delta_t = mxGetScalar(prhs[4]);
    int n = (int) mxGetScalar(prhs[5]);
    if (delta_t <= 0.0)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "delta_t needs to be larger than 0.0");
    if (n <= 0)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "n needs to be larger than 1");
    bool has_leak = false;
    double inv_leak = 0.0;
    if (nrhs >= 7) {
        inv_leak = mxGetScalar(prhs[6]);
        has_leak = (inv_leak != 0.0);
        if (inv_leak < 0.0)
            mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                              "inv_leak needs to be non-negative");
    }
    int rngseed = 0;
    if (nrhs >= 8)
        rngseed = (int) mxGetScalar(prhs[7]);
    if (nrhs > 8)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInputs",
                          "Too many input arguments");

    /* reserve space for output */
    plhs[0] = mxCreateDoubleMatrix(1, n, mxREAL);
    plhs[1] = mxCreateLogicalMatrix(1, n);
    double* t = mxGetPr(plhs[0]);
    mxLogical* b = mxGetLogicals(plhs[1]);

    /* perform sampling */
    DMBase* dm = nullptr;
    if (has_leak)
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t, inv_leak);
    else
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t);
    DMBase::rngeng_t rngeng;
    if (rngseed == 0) rngeng.seed(std::random_device()());
    else rngeng.seed(rngseed);
    for (int i = 0; i < n; ++i) {
        DMSample s = dm->rand(rngeng);
        t[i] = s.t();
        b[i] = s.upper_bound() ? 1 : 0;
    }
    delete dm;
}
Ejemplo n.º 29
0
void mexFunction(int nlhs, mxArray *plhs[], 
    int nrhs, const mxArray *prhs[])
{
   omp_set_num_threads(MAX_NUM_THREADS);

   // Extract input information
   uint32_t* users = (uint32_t*)mxGetData(prhs[0]);
   mwSize numExamples = mxGetM(prhs[0]);
   uint32_t* items = (uint32_t*)mxGetData(prhs[1]);
   const mxArray* samples = prhs[2];
   // Extract number of samples
   mwSize numSamples = mxGetM(samples);
   mwSize dimN = mxGetN(samples);
   if(dimN > numSamples)
      numSamples = dimN;
   int KU = mxGetM(mxGetField(samples, 0, "logthetaU"));
   int KM = mxGetM(mxGetField(samples, 0, "logthetaM"));
   int numFacs = mxGetM(mxGetField(samples, 0, "a"));
   int numUsers = mxGetN(mxGetField(samples, 0, "a"));
   int numItems = mxGetN(mxGetField(samples, 0, "b"));
   int numTopicFacs = mxGetM(mxGetField(samples, 0, "LambdaTildeU"));
   uint32_t* zU = (uint32_t*)mxGetData(prhs[3]);
   uint32_t* zM = (uint32_t*)mxGetData(prhs[4]);
   mxLogical* add = mxGetLogicals(prhs[5]);
   mxLogical addBase = add[0];
   mxLogical addTopicFactors = add[1];
   mxLogical addBiases = add[2];

   // Prepare output
   // New array auto-initialized to zeros
   plhs[0] = mxCreateDoubleMatrix(numExamples, 1, mxREAL);
   double* preds = mxGetPr(plhs[0]);

   int blasStride = 1;
  
   for(int t = 0; t < numSamples; t++){
      double* logthetaU = mxGetPr(mxGetField(samples, t, "logthetaU"));
      double* logthetaM = mxGetPr(mxGetField(samples, t, "logthetaM"));
      double* a = mxGetPr(mxGetField(samples, t, "a"));
      double* b = mxGetPr(mxGetField(samples, t, "b"));
      double* c = mxGetPr(mxGetField(samples, t, "c"));
      double* d = mxGetPr(mxGetField(samples, t, "d"));
      double* xi = mxGetPr(mxGetField(samples, t, "xi"));
      double* chi = mxGetPr(mxGetField(samples, t, "chi"));

      // Incorporate MF prediction and biases
#pragma omp parallel for
      for(mwSize e = 0; e < numExamples; e++){
	 int u = users[e]-1;
	 int j = items[e]-1;
	 
	 double* cVec = c + numTopicFacs*u;
	 double* dVec = d + numTopicFacs*j;
	 int numTopicFacsTimesNumUsers = numTopicFacs*numUsers;
	 int numTopicFacsTimesNumItems = numTopicFacs*numItems;
	 // Form prediction
	 if(addBase){
	    preds[e] += ddot(&numFacs, a + numFacs*u, &blasStride, 
			     b + numFacs*j, &blasStride);
	 }
	 if(addTopicFactors && (numTopicFacs > 0) && (KU > 0) && (KM > 0)){
	    if(zU != NULL && zM != NULL){
	       // Use provided topics
	       preds[e] += ddot(&numTopicFacs, cVec+
				numTopicFacsTimesNumUsers*(zM[e]-1), &blasStride, 
				dVec+numTopicFacsTimesNumItems*(zU[e]-1), &blasStride);
	    }
	    else{
	       // Integrate over topics
	       preds[e] += integrateFactorVectors(cVec, dVec,
						  logthetaU + u*KU,
						  logthetaM + j*KM, 
						  numTopicFacs, 
						  numTopicFacsTimesNumUsers,
						  numTopicFacsTimesNumItems,
						  KU, KM);
	    }
	 }
	 if(addBiases){
	    preds[e] += xi[u] + chi[j]; 
	 }
      }
   }
   if(numSamples > 1){
      // Average over all sample predictions
      for(mwSize e = 0; e < numExamples; e++)
	 preds[e] /= numSamples;
   }
}
Ejemplo n.º 30
0
//-------------------------------------------------------------------
void mexFunction(int POutputCount,  mxArray* POutput[], int PInputCount, const mxArray *PInputs[])
{
    	const int	*SZ;	    
    	double* 	LInput;
    	double* 	LInputI;
    	double* 	LOutputSum;
    	double* 	LOutputSumI;
    	double* 	LOutputCount;
    	double* 	LOutputSum2;
    	double* 	LOutputSum4;
    	double  	x, x2;
    	unsigned long   LCount, LCountI;
    	double  	LSum, LSum2, LSum4;

    	unsigned	DIM = 0; 
    	unsigned long	D1, D2, D3; 	// NN; 	//  	
    	unsigned    	ND, ND2;	// number of dimensions: input, output
    	unsigned long	ix1, ix2;	// index to input and output
    	unsigned    	j, k, l;	// running indices 
    	int 		*SZ2;		// size of output 	    


	// check for proper number of input and output arguments
	if ((PInputCount <= 0) || (PInputCount > 2))
	        mexErrMsgTxt("SumSkipNan.MEX requires 1 or 2 arguments.");
	if (POutputCount > 4)
	        mexErrMsgTxt("SumSkipNan.MEX has 1 to 4 output arguments.");

	// get 1st argument
	if(mxIsDouble(PInputs[0]))
		LInput  = mxGetPr(PInputs[0]);
	else 	
		mexErrMsgTxt("First argument must be DOUBLE.");

	if(mxIsLogical(PInputs[0]))
		LInput  = (double*)mxGetLogicals(PInputs[0]);
	else if(mxIsNumeric(PInputs[0]))
		LInput  = mxGetPr(PInputs[0]);
	else if(mxIsSparse(PInputs[0]))
		LInput  = mxGetPr(PInputs[0]);
	else if(mxIsInt8(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsUint8(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsInt16(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsUint16(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsInt32(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsUint32(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else
		mexErrMsgTxt("First argument must be NUMERIC.");

	if(mxIsComplex(PInputs[0]))
		LInputI = mxGetPi(PInputs[0]);
	if(mxIsComplex(PInputs[0]) & (POutputCount > 3))
	        mexErrMsgTxt("More than 3 output arguments only supported for REAL data ");

    	// get 2nd argument
    	if  (PInputCount == 2){
 	       	switch (mxGetNumberOfElements(PInputs[1])) {
		case 0: x = 0.0; 		// accept empty element
			break;
		case 1: x = (mxIsNumeric(PInputs[1]) ? mxGetScalar(PInputs[1]) : -1.0); 
			break;
		default:x = -1.0;		// invalid 
		}
		if ((x < 0) || (x > 65535) || (x != floor(x))) 
			mexErrMsgTxt("Error SUMSKIPNAN.MEX: DIM-argument must be a positive integer scalar");

		DIM = (unsigned)floor(x);	
	}

	// get size 
    	ND = mxGetNumberOfDimensions(PInputs[0]);	
    	// NN = mxGetNumberOfElements(PInputs[0]);
    	SZ = mxGetDimensions(PInputs[0]);		

	// if DIM==0 (undefined), look for first dimension with more than 1 element. 
	for (k = 0; (DIM < 1) && (k < ND); k++) 
		if (SZ[k]>1) DIM = k+1;
	
	if (DIM < 1) DIM=1;		// in case DIM is still undefined 

	ND2 = (ND>DIM ? ND : DIM);	// number of dimensions of output 

	SZ2 = (int*)mxCalloc(ND2, sizeof(int)); // allocate memory for output size

	for (j=0; j<ND; j++)		// copy size of input;  
		SZ2[j] = SZ[j]; 	
	for (j=ND; j<ND2; j++)		// in case DIM > ND, add extra elements 1 
		SZ2[j] = 1; 	

    	for (j=0, D1=1; j<DIM-1; D1=D1*SZ2[j++]); 	// D1 is the number of elements between two elements along dimension  DIM  
	D2 = SZ2[DIM-1];		// D2 contains the size along dimension DIM 	
    	for (j=DIM, D3=1;  j<ND; D3=D3*SZ2[j++]); 	// D3 is the number of blocks containing D1*D2 elements 

	SZ2[DIM-1] = 1;		// size of output is same as size of input but SZ(DIM)=1;

	    // create outputs
	#define TYP mxDOUBLE_CLASS

	if(mxIsComplex(PInputs[0]))
	{	POutput[0] = mxCreateNumericArray(ND2, SZ2, TYP, mxCOMPLEX);
		LOutputSum = mxGetPr(POutput[0]);
		LOutputSumI= mxGetPi(POutput[0]);
    	}
	else 
	{	POutput[0] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
		LOutputSum = mxGetPr(POutput[0]);
    	}

    	if (POutputCount >= 2){
		POutput[1] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
        	LOutputCount = mxGetPr(POutput[1]);
    	}
    	if (POutputCount >= 3){
		POutput[2] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
        	LOutputSum2  = mxGetPr(POutput[2]);
    	}
    	if (POutputCount >= 4){
		POutput[3] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
        	LOutputSum4  = mxGetPr(POutput[3]);
    	}

	mxFree(SZ2);

	// OUTER LOOP: along dimensions > DIM
	for (l = 0; l<D3; l++) 	
    	{
		ix2 =   l*D1;	// index for output 
		ix1 = ix2*D2;	// index for input 

		// Inner LOOP: along dimensions < DIM
		for (k = 0; k<D1; k++, ix1++, ix2++) 	
		{
		        LCount = 0;
			LSum   = 0.0;
			LSum2  = 0.0;
			LSum4  = 0.0;
	        	    		
			// LOOP  along dimension DIM
	    		for (j=0; j<D2; j++) 	
			{
				x = LInput[ix1 + j*D1];
        	        	if (!mxIsNaN(x))
				{
					LCount++; 
					LSum += x; 
					x2 = x*x;
					LSum2 += x2; 
					LSum4 += x2*x2; 
				}
			}
			LOutputSum[ix2] = LSum;
            		if (POutputCount >= 2)
                		LOutputCount[ix2] = (double)LCount;
            		if (POutputCount >= 3)
                		LOutputSum2[ix2] = LSum2;
            		if (POutputCount >= 4)
                		LOutputSum4[ix2] = LSum4;

			if(mxIsComplex(PInputs[0]))
			{
				LSum = 0.0;	
	    			LCountI = 0;
				LSum2  = 0.0;
				for (j=0; j<D2; j++) 	
				{
					x = LInputI[ix1 + j*D1];
        	        		if (!mxIsNaN(x))
					{
						LCountI++; 
						LSum  += x; 
						LSum2 += x*x; 
					}
				}
				LOutputSumI[ix2] = LSum;
				if (LCount != LCountI)
			            	mexErrMsgTxt("Number of NaNs is different for REAL and IMAG part");
	            		if (POutputCount >= 3)
        	        		LOutputSum2[ix2] += LSum2;
			}
		}
	}
}