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);
}
/* Function: mdlCheckParameters =============================================
 * Abstract:
 *    Validate our parameters to verify:
 *     o The numerator must be of a lower order than the denominator.
 *     o The sample time must be a real positive nonzero value.
 */
static void mdlCheckParameters(SimStruct *S)
{
	//  SFUNPRINTF("Calling mdlCheckParameters");

	// Tsim
	if (mxIsEmpty( ssGetSFcnParam(S,0)) ||
			mxIsSparse( ssGetSFcnParam(S,0)) ||
			mxIsComplex( ssGetSFcnParam(S,0)) ||
			mxIsLogical( ssGetSFcnParam(S,0)) ||
			!mxIsNumeric( ssGetSFcnParam(S,0)) ||
			!mxIsDouble( ssGetSFcnParam(S,0)) ||
			mxGetNumberOfElements(ssGetSFcnParam(S,0)) != 1) {
		ssSetErrorStatus(S,"Simulation time must be a single double Value");
		return;
	}

	// Vrep services base name
	if (!mxIsChar( ssGetSFcnParam(S,1)) ) {
		ssSetErrorStatus(S,"Vrep services base name must be a char array (string)");
		return;
	}

	// wait topic name
	if (!mxIsChar( ssGetSFcnParam(S,2)) ) {
		ssSetErrorStatus(S,"Wait topic name must be a char array (string)");
		return;
	}

	// wait timeout
	if (mxIsEmpty( ssGetSFcnParam(S,3)) ||
			mxIsSparse( ssGetSFcnParam(S,3)) ||
			mxIsComplex( ssGetSFcnParam(S,3)) ||
			mxIsLogical( ssGetSFcnParam(S,3)) ||
			!mxIsNumeric( ssGetSFcnParam(S,3)) ||
			!mxIsDouble( ssGetSFcnParam(S,3)) ||
			mxGetNumberOfElements(ssGetSFcnParam(S,3)) != 1) {
		ssSetErrorStatus(S,"Wait timeout must be a single double Value");
		return;
	}

	// wait extra_wait
	if (mxIsEmpty( ssGetSFcnParam(S,4)) ||
			mxIsSparse( ssGetSFcnParam(S,4)) ||
			mxIsComplex( ssGetSFcnParam(S,4)) ||
			mxIsLogical( ssGetSFcnParam(S,4)) ||
			!mxIsNumeric( ssGetSFcnParam(S,4)) ||
			!mxIsDouble( ssGetSFcnParam(S,4)) ||
			mxGetNumberOfElements(ssGetSFcnParam(S,4)) != 1) {
		ssSetErrorStatus(S,"Extra wait time must be a single double Value");
		return;
	}

}
Ejemplo n.º 3
0
  /* Function: mdlCheckParameters =============================================
   * Abstract:
   *    Validate our parameters to verify:
   *     o The numerator must be of a lower order than the denominator.
   *     o The sample time must be a real positive nonzero value.
   */
  static void mdlCheckParameters(SimStruct *S)
  {
    //  SFUNPRINTF("Calling mdlCheckParameters");
    
    // Tsim
    if (mxIsEmpty( ssGetSFcnParam(S,0)) ||
            mxIsSparse( ssGetSFcnParam(S,0)) ||
            mxIsComplex( ssGetSFcnParam(S,0)) ||
            mxIsLogical( ssGetSFcnParam(S,0)) ||
            !mxIsNumeric( ssGetSFcnParam(S,0)) ||
            !mxIsDouble( ssGetSFcnParam(S,0)) ||
            mxGetNumberOfElements(ssGetSFcnParam(S,0)) != 1) {
        ssSetErrorStatus(S,"Simulation time must be a single double Value");
        return;
    }

    // Prefix Topic
    if (!mxIsChar( ssGetSFcnParam(S,1)) ) {
        ssSetErrorStatus(S,"Prefix value must be char array (string)");
        return;
    }

    // Robot Array
    if (mxIsEmpty( ssGetSFcnParam(S,2)) ||
            mxIsSparse( ssGetSFcnParam(S,2)) ||
            mxIsComplex( ssGetSFcnParam(S,2)) ||
            mxIsLogical( ssGetSFcnParam(S,2)) ||
            !mxIsChar( ssGetSFcnParam(S,2)) ) {
        ssSetErrorStatus(S,"Robot Vector must be a char vector of robot ids");
        return;
    }

    // Postfix Topic
    if (!mxIsChar( ssGetSFcnParam(S,3)) ) {
        ssSetErrorStatus(S,"Postfix value must be char array (string)");
        return;
    }

    // N. of dofs
    if (mxIsEmpty( ssGetSFcnParam(S,4)) ||
            mxIsSparse( ssGetSFcnParam(S,4)) ||
            mxIsComplex( ssGetSFcnParam(S,4)) ||
            mxIsLogical( ssGetSFcnParam(S,4)) ||
            !mxIsChar( ssGetSFcnParam(S,4)) ||
            mxGetNumberOfElements(ssGetSFcnParam(S,4)) != 1) {
        ssSetErrorStatus(S,"N. of dofs must be a char");
        return;
    }

  }
Ejemplo n.º 4
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{  
  // Check inputs to mex function
  if (nlhs != 1 || nrhs < 2 || nrhs > 3) {
    mexEvalString("help cv.medianFilter");
    mexErrMsgIdAndTxt ( "medianFilter:usage", "Incorrect number of inputs/outputs provided." );
  }


  // Parse input
  const mxArray*              image         = prhs[0];
  const mxArray*              mask          = prhs[1];
  const mxArray*              selection     = nrhs > 2 ? prhs[2] : 0;

  if (mxGetNumberOfDimensions(image) != 2)
    mexErrMsgIdAndTxt("medianFilter:image", "Only 2D images are supported for now.");
  if (mxIsComplex(image))
    mexErrMsgIdAndTxt("medianFilter:image", "Only real valued images are supported for now.");

  if (!mxIsLogical(mask))
    mexErrMsgIdAndTxt("medianFilter:mask", "mask must be boolean.");
  if (mxGetM(mask) % 2 == 0)
    mexErrMsgIdAndTxt("medianFilter:mask", "mask must have an odd number of rows.");
  if (mxGetN(mask) % 2 == 0)
    mexErrMsgIdAndTxt("medianFilter:mask", "mask must have an odd number of columns.");

  const bool*                 isSelected    = 0;
  if (selection) {
    if (!mxIsLogical(selection))
      mexErrMsgIdAndTxt("weightedSumFilter:selection", "selection must be a logical matrix.");
    if (mxGetNumberOfElements(selection) != mxGetNumberOfElements(image))
      mexErrMsgIdAndTxt("weightedSumFilter:selection", "selection must have the same number of elements as image.");
    isSelected                = (const bool*) mxGetData(selection);
  }


  //---------------------------------------------------------------------------

  // Create output structure
  mxArray*                    filtered      = mxCreateNumericArray( mxGetNumberOfDimensions(image)
                                                                  , mxGetDimensions(image)
                                                                  , mxGetClassID(image)
                                                                  , mxREAL
                                                                  );
  plhs[0]                     = filtered;

  // Create filter class and process
  applyFilter<MedianFilter2D>(image, mxGetData(filtered), isSelected, mask);
}
Ejemplo n.º 5
0
void mexFunction(int nOut, mxArray *pOut[],
		 int nIn, const mxArray *pIn[])
{
  int rows, cols, len, i, j;
  mxLogical *indataGT, *indataMask, *indataCare;
  int intersect=0;
  int all=0;
  double *outdata;

  if((nIn != 3) || (nOut != 1))
    mexErrMsgTxt("Usage: intersection = overlap_care(GT, mask, care)");
  for (i=0;i<3;i++)
    if (!mxIsLogical(pIn[i]) || mxGetNumberOfDimensions(pIn[i]) != 2) {
            mexErrMsgTxt("Usage: th argument must be a logical matrix");
        }
  
  rows = mxGetM(pIn[0]);
  cols = mxGetN(pIn[0]);
  len=rows*cols;
  indataGT = (bool*) mxGetData(pIn[0]);
  indataMask = (bool*) mxGetData(pIn[1]);
  indataCare = (bool*) mxGetData(pIn[2]);
  
  
  for(i=0;i<len; i++){
        intersect+=indataGT[i] && indataMask[i] && indataCare[i];
        all+=(indataGT[i] || indataMask[i]) && indataCare[i];
      }
  pOut[0]=mxCreateDoubleMatrix(1,1, mxREAL);
  outdata=mxGetPr(pOut[0]);
  outdata[0]=((double)intersect)/all;

}
Ejemplo n.º 6
0
void xglhwconversion_mexgen (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check inputs
    if (nrhs != 3)
        mexErrMsgTxt ("This function requires 3 arguments.");

    // Check outputs
    if (nlhs > 1)
        mexErrMsgTxt ("Too many return values were specified.");

    // Check input types
    if (!mxIsDouble (prhs[0]))
        mexErrMsgTxt ("Input 1 must be double.");
    if (mxIsComplex (prhs[0]))
        mexErrMsgTxt ("Input 1 may not be complex.");

    if (!mxIsDouble (prhs[1]))
        mexErrMsgTxt ("Input 2 must be double.");
    if (mxIsComplex (prhs[1]))
        mexErrMsgTxt ("Input 2 may not be complex.");

    if (!mxIsDouble (prhs[2]))
        mexErrMsgTxt ("Input 3 must be double.");
    if (mxIsComplex (prhs[2]))
        mexErrMsgTxt ("Input 3 may not be complex.");

    xglhwconversion (nlhs, plhs, nrhs, prhs);

    // Check output types
    if (!plhs[0])
        mexErrMsgTxt ("Output 1 was not allocated.");
    if (!mxIsLogical (plhs[0]))
        mexErrMsgTxt ("Output 1 must be logical.");

}
Ejemplo n.º 7
0
void xglgetrasterstatus_mexgen (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check inputs
    if (nrhs != 1)
        mexErrMsgTxt ("This function requires 1 arguments.");

    // Check outputs
    if (nlhs != 2)
        mexErrMsgTxt ("This function requires 2 return values.");

    // Check input types
    if (!mxIsDouble (prhs[0]))
        mexErrMsgTxt ("Input 1 must be double.");
    if (mxIsComplex (prhs[0]))
        mexErrMsgTxt ("Input 1 may not be complex.");

    xglgetrasterstatus (nlhs, plhs, nrhs, prhs);

    // Check output types
    if (!plhs[0])
        mexErrMsgTxt ("Output 1 was not allocated.");
    if (!mxIsLogical (plhs[0]))
        mexErrMsgTxt ("Output 1 must be logical.");

    if (!plhs[1])
        mexErrMsgTxt ("Output 2 was not allocated.");
    if (!mxIsDouble (plhs[1]))
        mexErrMsgTxt ("Output 2 must be double.");
    if (mxIsComplex (plhs[1]))
        mexErrMsgTxt ("Output 2 may not be complex.");

}
Ejemplo n.º 8
0
int mxGetElementSize(const mxArray *ptr)
{
    if (mxIsChar(ptr))
    {
        return sizeof(wchar_t*);
    }
    else if (mxIsLogical(ptr))
    {
        return sizeof(int);
    }
    else if (mxIsDouble(ptr))
    {
        return sizeof(double);
    }
    else if (mxIsSparse(ptr))
    {
        return sizeof(double);
    }
    else if (mxIsInt8(ptr))
    {
        return sizeof(char);
    }
    else if (mxIsInt16(ptr))
    {
        return sizeof(short);
    }
    else if (mxIsInt32(ptr))
    {
        return sizeof(int);
    }
    else if (mxIsInt64(ptr))
    {
        return sizeof(long long);
    }
    else if (mxIsUint8(ptr))
    {
        return sizeof(unsigned char);
    }
    else if (mxIsUint16(ptr))
    {
        return sizeof(unsigned short);
    }
    else if (mxIsUint32(ptr))
    {
        return sizeof(unsigned int);
    }
    else if (mxIsUint64(ptr))
    {
        return sizeof(unsigned long long);
    }
    else if (mxIsCell(ptr))
    {
        return sizeof(types::InternalType*);
    }
    else if (mxIsStruct(ptr))
    {
        return sizeof(types::SingleStruct*);
    }
    return 0;
}
Ejemplo n.º 9
0
const char *mxGetClassName(const mxArray *ptr)
{
    if (mxIsDouble(ptr))
    {
        return "double";
    }
    if (mxIsChar(ptr))
    {
        return "char";
    }
    if (mxIsLogical(ptr))
    {
        return "bool";
    }
    if (mxIsSparse(ptr))
    {
        return "sparse";
    }
    if (mxIsInt8(ptr))
    {
        return "int8";
    }
    if (mxIsInt16(ptr))
    {
        return "int16";
    }
    if (mxIsInt32(ptr))
    {
        return "int32";
    }
    if (mxIsInt64(ptr))
    {
        return "int64";
    }
    if (mxIsUint8(ptr))
    {
        return "uint8";
    }
    if (mxIsUint16(ptr))
    {
        return "uint16";
    }
    if (mxIsUint32(ptr))
    {
        return "uint32";
    }
    if (mxIsUint64(ptr))
    {
        return "uint64";
    }
    if (mxIsCell(ptr))
    {
        return "cell";
    }
    if (mxIsStruct(ptr))
    {
        return "struct";
    }
    return "unknown";
}
Ejemplo n.º 10
0
IGL_INLINE void igl::matlab::validate_arg_logical(
    const int i, const int nrhs, const mxArray * prhs[], const char * name)
{
  requires_arg(i,nrhs,name);
  mexErrMsgTxt(mxIsLogical(prhs[i+1]),
    C_STR("Parameter '"<<name<<"' requires Logical argument"));
}
Ejemplo n.º 11
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.º 12
0
void mxSetImagData(mxArray *array_ptr, void *data_ptr)
{
    if (mxIsChar(array_ptr))
    {
        ((String *)array_ptr)->setImg((wchar_t **)data_ptr);
    }
    else if (mxIsDouble(array_ptr))
    {
        ((Double *)array_ptr)->setImg((double *)data_ptr);
    }
    else if (mxIsInt8(array_ptr))
    {
        ((Int8 *)array_ptr)->setImg((char *)data_ptr);
    }
    else if (mxIsInt16(array_ptr))
    {
        ((Int16 *)array_ptr)->setImg((short *)data_ptr);
    }
    else if (mxIsInt32(array_ptr))
    {
        ((Int32 *)array_ptr)->setImg((int *)data_ptr);
    }
    else if (mxIsInt64(array_ptr))
    {
        ((Int64 *)array_ptr)->setImg((long long *)data_ptr);
    }
    else if (mxIsLogical(array_ptr))
    {
        ((Bool *)array_ptr)->setImg((int *)data_ptr);
    }
    // else if (mxIsSingle(array_ptr)) {
    //   ((Float *) array_ptr)->setImg((float *) data_ptr);
    // }
    else if (mxIsUint8(array_ptr))
    {
        ((UInt8 *)array_ptr)->setImg((unsigned char *)data_ptr);
    }
    else if (mxIsUint16(array_ptr))
    {
        ((UInt16 *)array_ptr)->setImg((unsigned short *)data_ptr);
    }
    else if (mxIsUint32(array_ptr))
    {
        ((UInt32 *)array_ptr)->setImg((unsigned int *)data_ptr);
    }
    else if (mxIsUint64(array_ptr))
    {
        ((UInt64 *)array_ptr)->setImg((unsigned long long *) data_ptr);
    }
}
Ejemplo n.º 13
0
Archivo: mex.c Proyecto: a4a881d4/aloe
void format_input_vector(void *buffer, const mxArray *in, int len) {
	double *in_real, *in_imag;
	char *in_bit;
	float *f_buffer = buffer;
	_Complex float *c_buffer = buffer;
	char *b_buffer = buffer;
	int i;

	if (len>input_max_samples) {
		mexErrMsgTxt("Input vector too large");
	}

	if (input_sample_sz == sizeof(_Complex float)) {
		if (!mxIsDouble(in)){
			mexErrMsgTxt("Module input is complex. Matlab signal must be complex too.\n");
		}
		in_real = mxGetPr(in);
		in_imag = in_real;
		if (mxIsComplex(in))
			in_imag = mxGetPi(in);
		for (i=0;i<len;i++) {
			__real__ c_buffer[i] = (float) in_real[i];
			if (mxIsComplex(in))
				__imag__ c_buffer[i] = (float) in_imag[i];
			else
				__imag__ c_buffer[i] = 0;
		}
	} else if (input_sample_sz == sizeof(float)) {
		if (!mxIsDouble(in)){
			mexErrMsgTxt("Module input is real. Matlab signal must be real too.\n");
		}
		in_real = mxGetPr(in);
		for (i=0;i<len;i++) {
			f_buffer[i] = (float) in_real[i];
		}
	} else if (input_sample_sz == sizeof(char)) {
		if (!mxIsLogical(in)) {
			mexErrMsgTxt("Module input is bitstream. Matlab signal must be logical.\n");
		}
		in_bit = (char*) mxGetData(in);
		for (i=0;i<len;i++) {
			b_buffer[i] = in_bit[i];
		}
	} else {
		mexErrMsgTxt("Matlab signal type not supported\n");
	}

}
Ejemplo n.º 14
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.º 15
0
static void ImageOverSegmentation_maskToBox( MEX_ARGS ) {
    if( nrhs != 2 || !mxIsLogical(prhs[1]) ) {
        mexErrMsgTxt( "Expected a ImageOverSegmentation and mask array" );
        return ;
    }
    if( nlhs != 1 ) {
        mexErrMsgTxt( "Expected a single return argument" );
        return ;
    }
    std::shared_ptr<ImageOverSegmentation> os = mat2Ptr<ImageOverSegmentation>( prhs[0] );
    RMatrixXi r = os->maskToBox( MatrixXb::Map( (mxLogical*)mxGetData(prhs[1]), mxGetM(prhs[1]), mxGetN(prhs[1]) ) );
    // Create and write the resulting segmentation
    mwSize dims[2] = {(mwSize)r.rows(), (mwSize)r.cols()};
    plhs[0] = mxCreateNumericArray( 2, dims, mxINT32_CLASS, mxREAL );
    MatrixXi::Map( (int*)mxGetData(plhs[0]), r.rows(), r.cols() ) = r;
}
Ejemplo n.º 16
0
void mxSetImagData(mxArray *array_ptr, void *data_ptr)
{
    if (mxIsChar(array_ptr))
    {
        ((types::String *)array_ptr)->setImg((wchar_t **)data_ptr);
    }
    else if (mxIsDouble(array_ptr))
    {
        ((types::Double *)array_ptr)->setImg((double *)data_ptr);
    }
    else if (mxIsInt8(array_ptr))
    {
        ((types::Int8 *)array_ptr)->setImg((char *)data_ptr);
    }
    else if (mxIsInt16(array_ptr))
    {
        ((types::Int16 *)array_ptr)->setImg((short *)data_ptr);
    }
    else if (mxIsInt32(array_ptr))
    {
        ((types::Int32 *)array_ptr)->setImg((int *)data_ptr);
    }
    else if (mxIsInt64(array_ptr))
    {
        ((types::Int64 *)array_ptr)->setImg((long long *)data_ptr);
    }
    else if (mxIsLogical(array_ptr))
    {
        ((types::Bool *)array_ptr)->setImg((int *)data_ptr);
    }
    else if (mxIsUint8(array_ptr))
    {
        ((types::UInt8 *)array_ptr)->setImg((unsigned char *)data_ptr);
    }
    else if (mxIsUint16(array_ptr))
    {
        ((types::UInt16 *)array_ptr)->setImg((unsigned short *)data_ptr);
    }
    else if (mxIsUint32(array_ptr))
    {
        ((types::UInt32 *)array_ptr)->setImg((unsigned int *)data_ptr);
    }
    else if (mxIsUint64(array_ptr))
    {
        ((types::UInt64 *)array_ptr)->setImg((unsigned long long *) data_ptr);
    }
}
Ejemplo n.º 17
0
void mxtestlogical (const mxArray* testMxArray, int argnum=0) {
 
   if (!mxIsLogical(testMxArray))
   {
       if (argnum > 0)
       {
           mexErrMsgIdAndTxt("CPP:mxtestnumeric",
                "Input argument type is not logical.", argnum);
       }
       else
       {
           mexErrMsgIdAndTxt("CPP:mxtestnumeric",
                "Input argument type is not logical.");
       }
   } 
   
}
Ejemplo n.º 18
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.º 19
0
/* Function: mdlCheckParameters =============================================
 * Abstract:
 *    Validate our parameters to verify:
 *     o The numerator must be of a lower order than the denominator.
 *     o The sample time must be a real positive nonzero value.
 */
static void mdlCheckParameters(SimStruct *S) {
	//  SFUNPRINTF("Calling mdlCheckParameters");

	// Tsim
	if (mxIsEmpty(ssGetSFcnParam(S, 0)) || mxIsSparse(ssGetSFcnParam(S, 0))
			|| mxIsComplex(ssGetSFcnParam(S, 0))
			|| mxIsLogical(ssGetSFcnParam(S, 0))
			|| !mxIsNumeric(ssGetSFcnParam(S, 0))
			|| !mxIsDouble(ssGetSFcnParam(S, 0))
			|| mxGetNumberOfElements(ssGetSFcnParam(S, 0)) != 1) {
		ssSetErrorStatus(S, "Simulation time must be a single double Value");
		return;
	}

	// Topic
	if (!mxIsChar(ssGetSFcnParam(S, 1))) {
		ssSetErrorStatus(S, "Topic value must be char array (string)");
		return;
	}

}
Ejemplo n.º 20
0
void GB_mx_mxArray_to_array    // convert mxArray to array
(
    const mxArray *Xmatlab,     // input MATLAB array
    // output:
    void **X,                   // pointer to numerical values
    int64_t *nrows,             // number of rows of X
    int64_t *ncols,             // number of columns of X
    mxClassID *xclass,          // MATLAB class of X
    GrB_Type *xtype             // GraphBLAS type of X, NULL if error
)
{

    *X = NULL ;
    *nrows = 0 ;
    *ncols = 0 ;
    *xclass = mxUNKNOWN_CLASS ;
    *xtype = NULL ;

    if (!(mxIsNumeric (Xmatlab) || mxIsLogical (Xmatlab)))
    {
        mexWarnMsgIdAndTxt ("GB:warn","input must be numeric or logical array");
    }
    if (mxIsSparse (Xmatlab))
    {
        mexWarnMsgIdAndTxt ("GB:warn","input cannot be sparse") ;
    }

    if (mxIsComplex (Xmatlab))
    {
        // user-defined Complex type
        // make a deep copy of the MATLAB complex dense matrix
        int64_t nel = mxGetNumberOfElements (Xmatlab) ;
        GB_MALLOC_MEMORY (double *XX, nel+1, sizeof (double complex)) ;
        GB_mx_complex_merge (nel, XX, Xmatlab) ;
        *X = XX ;
        *xclass = mxDOUBLE_CLASS ;
        *xtype = Complex ;
    }
    else
    {
Ejemplo n.º 21
0
mxArray* test_any_true(const mxArray *mxV)
{
    if (mxIsEmpty(mxV))
    {
        return mxCreateLogicalScalar((mxLogical)false);
    }
    
    if (!mxIsLogical(mxV))
    {
        mexErrMsgIdAndTxt("dmtoolbox:anytrue:invalidarg", 
            "The input array to anytrue should be logical or empty");
    }
    
    int n = mxGetNumberOfElements(mxV);
    const mxLogical* values = (const mxLogical*)mxGetData(mxV);
    
    for (int i = 0; i < n; ++i)
    {
        if (values[i]) return mxCreateLogicalScalar((mxLogical)true);
    }
    
    return mxCreateLogicalScalar((mxLogical)false);
}
Ejemplo n.º 22
0
void mexFunction(int nargout, mxArray *out[], int nargin, const mxArray *in[]) 
{

    /* declare variables */
    mwSize width, height, nsegms;
    mwSize *sizes;
    bool *segms;
    float *o1, *o2;
    
    /* check argument */
    if (nargin<1) {
        mexErrMsgTxt("One input argument required ( the segments in row * column * num_segments form )");
    }
    if (nargout>2) {
        mexErrMsgTxt("Too many output arguments");
    }
    /* sizes */
    sizes = (mwSize *)mxGetDimensions(in[0]);
    height = sizes[0];
    width = sizes[1];
    nsegms = sizes[2];

    if (!mxIsLogical(in[0]) || mxGetNumberOfDimensions(in[0]) != 3) {
        mexErrMsgTxt("Usage: segms must be a 3-dimensional logical matrix");
    }

    segms = (bool *) mxGetData(in[0]);
    out[0] = mxCreateNumericMatrix(nsegms, 1 ,mxSINGLE_CLASS, mxREAL);
    out[1] = mxCreateNumericMatrix(nsegms, 1 ,mxSINGLE_CLASS, mxREAL);
    if (out[0]==NULL || out[1]==NULL) {
	    mexErrMsgTxt("Not enough memory for the output matrix");
    }
    o1 = (float *) mxGetPr(out[0]);
    o2 = (float *) mxGetPr(out[1]);

    compute_centroid(segms, height, width, nsegms, o1, o2);
}
Ejemplo n.º 23
0
  /* Function: mdlCheckParameters =============================================
   * Abstract:
   *    Validate our parameters to verify they are okay.
   */
  static void mdlCheckParameters(SimStruct *S)
  {
      int  i;
      bool badParam = false;

      /* All parameters must be positive non-zero integers */
      for (i = 0; i < ssGetSFcnParamsCount(S); i++) {
          const mxArray *m = ssGetSFcnParam(S,i);

          if (mxGetNumberOfElements(m) != 1 ||
              !mxIsNumeric(m) || !mxIsDouble(m) || mxIsLogical(m) ||
              mxIsComplex(m) || mxIsSparse(m) || !mxIsFinite(mxGetPr(m)[0])) {
              badParam = true;
              break;
          }
          if (i < NKPARAMS) {
              int ival;
              if (((ival=(int_T)mxGetPr(m)[0]) <= 0) ||
                  (real_T)ival != mxGetPr(m)[0]) {
                  badParam = true;
                  break;
              }
          } else if (mxGetPr(m)[0] <= 0.0) {
              badParam = true;
              break;
          }
      }

      if (badParam) {
          ssSetErrorStatus(S,"All parameters must be positive non-zero "
                           "values. First three must be integers and the "
                           "optional fourth must be a discrete sample "
                           "time");
          return;
      }
  }
Ejemplo n.º 24
0
mxArray* count_false(const mxArray* mxV)
{
    if (mxIsEmpty(mxV))
    {
        return mxCreateDoubleScalar(0);
    }
    
    if (!mxIsLogical(mxV))
    {
        mexErrMsgIdAndTxt("dmtoolbox:countfalse:invalidarg", 
            "The input array to countfalse should be logical or empty");
    }
    
    int n = mxGetNumberOfElements(mxV);
    const mxLogical* values = (const mxLogical*)mxGetData(mxV);
    unsigned long c = 0;
    
    for (int i = 0; i < n; ++i)
    {
        if (!values[i]) ++c;
    }
    
    return mxCreateDoubleScalar((double)c);
}
Ejemplo n.º 25
0
void mexFunction( int nlhs, mxArray *plhs[], 
                  int nrhs, const mxArray*prhs[] ) { 
  if (first) {
    mexPrintf("treeupdate using NUM_THREADS=%u\n",NUM_THREADS);
    mexEvalString("drawnow;");
    first=0;
  }

  if (nrhs != 14) {
      mexErrMsgTxt("Wrong number of arguments. Fail.");
      return;
  }

  if (nlhs != 1) {
      mexErrMsgTxt("Wrong number of outputs. Fail.");
      return;
  }

  if (! mxIsSparse (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Hashxtic must be sparse. Fail.");
    return;
  }

  if (mxIsSparse (OAS_MATRIX_IN)) {      
    mexErrMsgTxt("Oas must be dense. Fail.");
    return;
  }

  if (! mxIsSingle (OAS_MATRIX_IN)) {
    mexErrMsgTxt("Oas must be single. Fail.");
    return;
  }

  if (mxGetM (OAS_MATRIX_IN) != mxGetM (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Hashxtic and oas have incompatible shape. Fail.");
    return;
  }

  if (! mxIsSparse (FILTMAT_MATRIX_IN)) { 
    mexErrMsgTxt("Filtmat must be sparse. Fail.");
    return;
  }

  if (mxGetN (OAS_MATRIX_IN) != mxGetM (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Oas and filtmat have incompatible shape. Fail.");
    return;
  }

  if (! mxIsSparse (EXINDEX_MATRIX_IN)) { 
    mexErrMsgTxt("Exindex must be sparse. Fail.");
    return;
  }

  if (mxGetN (EXINDEX_MATRIX_IN) != mxGetN (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Exindex and filtmat have incompatible shape. Fail.");
    return;
  }
  
  if (! mxIsCell (BIAS_CELL_IN)) {
    mexErrMsgTxt("Bias must be cell array. Fail.");
    return;
  }

  for (mwIndex i = 0; i < mxGetNumberOfElements (BIAS_CELL_IN); ++i)
    {
      const mxArray* mybias = mxGetCell (BIAS_CELL_IN, i);

      if (mybias) {
        if (! mxIsSingle (mybias)) {
          mexErrMsgTxt("Bias must contain single arrays. Fail.");
        }

        break;
      }
    }

  if (mxIsSparse (MOMENTUM_MATRIX_IN)) {      
    mexErrMsgTxt("Momentum must be dense. Fail.");
    return;
  }

  if (! mxIsSingle (MOMENTUM_MATRIX_IN)) {
    mexErrMsgTxt("Momentum must be single. Fail.");
    return;
  }

  if (! mxIsCell (MOMENTUM_BIAS_CELL_IN)) {
    mexErrMsgTxt("Momentum bias must be cell array. Fail.");
    return;
  }

  for (mwIndex i = 0; i < mxGetNumberOfElements (MOMENTUM_BIAS_CELL_IN); ++i)
    {
      const mxArray* mymombias = mxGetCell (MOMENTUM_BIAS_CELL_IN, i);

      if (mymombias) {
        if (! mxIsSingle (mymombias)) {
          mexErrMsgTxt("Momentum bias must contain single arrays. Fail.");
        }

        break;
      }
    }

  if (! mxIsSparse (YTIC_MATRIX_IN)) {
    mexErrMsgTxt("Ytic must be sparse. Fail.");
    return;
  }

  if (mxGetN (YTIC_MATRIX_IN) != mxGetN (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Ytic and hashxtic have incompatible shapes. Fail.");
    return;
  }

  if (mxGetM (YTIC_MATRIX_IN) != mxGetM (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Ytic and filtmat have incompatible shapes. Fail.");
    return;
  }

  if (! mxIsSingle (C_VECTOR_IN)) {
    mexErrMsgTxt("C must be single. Fail.");
    return;
  }

  if (mxGetNumberOfElements (C_VECTOR_IN) != mxGetM (OAS_MATRIX_IN)) {
    mexErrMsgTxt("C and oas have incompatible shapes. Fail.");
    return;
  }
  
  if (! mxIsDouble (NODE_PERM_VECTOR_IN)) {
    mexErrMsgTxt("Node perm must be double. Fail.");
    return;
  }

  if (mxGetNumberOfElements (NODE_PERM_VECTOR_IN) != mxGetN (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Node perm and filtmat have incompatible shapes. Fail.");
    return;
  } 

  if (! mxIsDouble (EX_PERM_VECTOR_IN)) {
    mexErrMsgTxt("Example perm must be double. Fail.");
    return;
  }

  if (mxGetNumberOfElements (EX_PERM_VECTOR_IN) != mxGetN (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Example perm and hashxtic have incompatible shapes. Fail.");
    return;
  } 


  if (mxGetM (ETA_SCALAR_IN) != 1 || mxGetN (ETA_SCALAR_IN) != 1) {
    mexErrMsgTxt("Eta must be a double scalar. Fail.");
    return;
  }

  if (mxGetScalar (ETA_SCALAR_IN) <= 0) {
    mexErrMsgTxt("Eta must be positive. Fail.");
    return;
  }

  if (mxGetM (ALPHA_SCALAR_IN) != 1 || mxGetN (ALPHA_SCALAR_IN) != 1) {
    mexErrMsgTxt("Alpha must be a double scalar. Fail.");
    return;
  }

  if (mxGetScalar (ALPHA_SCALAR_IN) < 0 || mxGetScalar (ALPHA_SCALAR_IN) >= 1) {
    mexErrMsgTxt("Alpha must be in [0,1). Fail.");
    return;
  }

  if (! mxIsLogical (SOFTMAX_LOGICAL_IN) || mxGetM (SOFTMAX_LOGICAL_IN) != 1
      || mxGetN (SOFTMAX_LOGICAL_IN) != 1) {
    mexErrMsgTxt("Softmax option must be logical. Fail.");
    return;
  }

  NORM_DELTA_OUT = mxCreateNumericMatrix (1, 1, mxDOUBLE_CLASS, mxREAL);
  double* norm_delta_out = (double *) mxGetPr (NORM_DELTA_OUT);
  double* norm_deltas = (double*) mxCalloc(NUM_THREADS, sizeof(double));

  std::thread t[NUM_THREADS];

  if (mxIsLogicalScalarTrue (SOFTMAX_LOGICAL_IN)) {
    for (size_t i = 0; i + 1 < NUM_THREADS; ++i) {
      t[i] = std::thread (update<true>, prhs, norm_deltas + i, i, NUM_THREADS);
    }

    update<true> (prhs, norm_deltas + NUM_THREADS-1, NUM_THREADS-1, NUM_THREADS);
  }
  else {
    for (size_t i = 0; i + 1 < NUM_THREADS; ++i) {
      t[i] = std::thread (update<false>, prhs, norm_deltas + i, i, NUM_THREADS);
    }

    update<false> (prhs, norm_deltas + NUM_THREADS-1, NUM_THREADS-1, NUM_THREADS);
  }
  
  for (int i = 0; i + 1 < NUM_THREADS; ++i) {
    t[i].join ();
    norm_deltas[NUM_THREADS-1] += norm_deltas[i];
  }

  *norm_delta_out = norm_deltas[NUM_THREADS-1];

  return;
}
Ejemplo n.º 26
0
int get_SolverOptions(const mxArray *options,
                      booleantype *verbose, booleantype *errmsg,
                      int *mxiter, int *msbset, int *msbsetsub,
                      int *etachoice, int *mxnbcf,
                      double *eta, double *egamma, double *ealpha, double *mxnewtstep,
                      double *relfunc, double *fnormtol, double *scsteptol,
                      double **constraints,
                      booleantype *noInitSetup, booleantype *noMinEps)
{
    mxArray *opt;
    char *bufval;
    int i, buflen, status, m, n;
    double *tmp;

    /* Set default values (pass 0 values. KINSOL does the rest) */

    *mxiter = 0;
    *msbset = 0;
    *msbsetsub = 0;
    *mxnbcf = 0;
    *etachoice = KIN_ETACHOICE1;

    *eta = 0.0;
    *egamma = 0.0;
    *ealpha = 0.0;
    *mxnewtstep = 0.0;
    *relfunc = 0.0;
    *fnormtol = 0.0;
    *scsteptol = 0.0;

    *noInitSetup = FALSE;
    *noMinEps = FALSE;

    *constraints = NULL;

    *verbose = FALSE;
    *errmsg = TRUE;

    /* Return now if options was empty */

    if (mxIsEmpty(options)) return(0);

    /* User data */

    opt = mxGetField(options,0,"UserData");
    if ( !mxIsEmpty(opt) ) {
        mxDestroyArray(mtlb_data);
        mtlb_data = mxDuplicateArray(opt);
    }

    /* Integer values */

    opt = mxGetField(options,0,"MaxNumIter");
    if ( !mxIsEmpty(opt) )
        *mxiter = (int)*mxGetPr(opt);

    opt = mxGetField(options,0,"MaxNumSetups");
    if ( !mxIsEmpty(opt) )
        *msbset = (int)*mxGetPr(opt);

    opt = mxGetField(options,0,"MaxNumSubSetups");
    if ( !mxIsEmpty(opt) )
        *msbsetsub = (int)*mxGetPr(opt);

    opt = mxGetField(options,0,"MaxNumBetaFails");
    if ( !mxIsEmpty(opt) )
        *mxnbcf = (int)*mxGetPr(opt);

    opt = mxGetField(options,0,"EtaForm");
    if ( !mxIsEmpty(opt) ) {
        buflen = mxGetM(opt) * mxGetN(opt) + 1;
        bufval = mxCalloc(buflen, sizeof(char));
        status = mxGetString(opt, bufval, buflen);
        if(status != 0) {
            kimErrHandler(-999, "KINSOL", "KINInit", "Cannot parse EtaForm.", NULL);
            return(-1);
        }
        if(strcmp(bufval,"Type1"))         *etachoice = KIN_ETACHOICE1;
        else if(strcmp(bufval,"Type2"))    *etachoice = KIN_ETACHOICE2;
        else if(strcmp(bufval,"Constant")) *etachoice = KIN_ETACONSTANT;
        else {
            kimErrHandler(-999, "KINSOL", "KINInit", "EtaForm has an illegal value.", NULL);
            return(-1);
        }
    }

    /* Real values */

    opt = mxGetField(options,0,"Eta");
    if ( !mxIsEmpty(opt) )
        *eta = (double)*mxGetPr(opt);

    opt = mxGetField(options,0,"EtaAlpha");
    if ( !mxIsEmpty(opt) )
        *ealpha = (double)*mxGetPr(opt);

    opt = mxGetField(options,0,"EtaGamma");
    if ( !mxIsEmpty(opt) )
        *egamma = (double)*mxGetPr(opt);

    opt = mxGetField(options,0,"MaxNewtonStep");
    if ( !mxIsEmpty(opt) )
        *mxnewtstep = (double)*mxGetPr(opt);

    opt = mxGetField(options,0,"FuncRelErr");
    if ( !mxIsEmpty(opt) )
        *relfunc = (double)*mxGetPr(opt);

    opt = mxGetField(options,0,"FuncNormTol");
    if ( !mxIsEmpty(opt) )
        *fnormtol = (double)*mxGetPr(opt);

    opt = mxGetField(options,0,"ScaledStepTol");
    if ( !mxIsEmpty(opt) )
        *scsteptol = (double)*mxGetPr(opt);

    /* Boolean values */

    opt = mxGetField(options,0,"ErrorMessages");
    if ( !mxIsEmpty(opt) ) {
        if (!mxIsLogical(opt)) {
            kimErrHandler(-999, "KINSOL", "KINInit", "ErrorMessages is not a logical scalar.", NULL);
            return(-1);
        }
        if (mxIsLogicalScalarTrue(opt)) *errmsg = TRUE;
        else                            *errmsg = FALSE;
    }

    opt = mxGetField(options,0,"Verbose");
    if ( !mxIsEmpty(opt) ) {
        if (!mxIsLogical(opt)) {
            kimErrHandler(-999, "KINSOL", "KINInit", "Verbose is not a logical scalar.", NULL);
            return(-1);
        }
        if (mxIsLogicalScalarTrue(opt)) *verbose = TRUE;
        else                            *verbose = FALSE;
    }

    opt = mxGetField(options,0,"InitialSetup");
    if ( !mxIsEmpty(opt) ) {
        if (!mxIsLogical(opt)) {
            kimErrHandler(-999, "KINSOL", "KINInit", "InitialSetup is not a logical scalar.", NULL);
            return(-1);
        }
        if (mxIsLogicalScalarTrue(opt)) *noInitSetup = FALSE;
        else                            *noInitSetup = TRUE;
    }


    opt = mxGetField(options,0,"MinBoundEps");
    if ( !mxIsEmpty(opt) ) {
        if (!mxIsLogical(opt)) {
            kimErrHandler(-999, "KINSOL", "KINInit", "MinBoundEps is not a logical scalar.", NULL);
            return(-1);
        }
        if (mxIsLogicalScalarTrue(opt)) *noMinEps = FALSE;
        else                            *noMinEps = TRUE;
    }

    /* Constraints */

    opt = mxGetField(options,0,"Constraints");
    if ( !mxIsEmpty(opt) ) {
        m = mxGetM(opt);
        n = mxGetN(opt);
        if ( (n != 1) && (m != 1) ) {
            kimErrHandler(-999, "KINSOL", "KINInit", "constraints is not a vector.", NULL);
            return(-1);
        }
        if ( m > n ) n = m;
        if ( n != N ) {
            kimErrHandler(-999, "KINSOL", "KINInit", "constraints has wrong number of components.", NULL);
            return(-1);
        }
        tmp = mxGetPr(opt);
        *constraints = (double *) malloc(N*sizeof(double));
        for (i=0; i<N; i++) (*constraints)[i] = tmp[i];
    }

    /* We made it here without problems */

    return(0);
}
Ejemplo n.º 27
0
Archivo: pixCon.cpp Proyecto: 19bal/gad
void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int i, j, k, ndim, npix, nzmax;
    int *offset, *ir, *jc;
    double *out, *inp;
    char *mode;

    // check for proper number of arguments
    if (nrhs < 1) {
        mexErrMsgTxt("Must specify image dimensions.");
    }
    if (nlhs > 1) {
        mexErrMsgTxt("Too many output arguments.");
    }

    // check input
    if (!mxIsDouble(prhs[0])) {
        mexErrMsgTxt("First input must be type double.");
    }
    ndim = mxGetNumberOfElements(prhs[0]);
    if (ndim > 4) {
        mexErrMsgTxt("Number of dimensions exceeds design limit (4).");
    }

    // set up offset array
    inp = mxGetPr(prhs[0]);
    offset = (int*)mxMalloc((ndim+1)*sizeof(int));
    offset[0] = 1;
    for (i = 0; i < ndim; i++) {
        offset[i+1] = (int)(offset[i]*inp[i]);
    }
    npix = offset[ndim];
    //mexPrintf("Set up array.\n");

    // determine type of connection matrix
    if (nrhs > 1) {
        mode = (char*)mxGetPr(prhs[1]);
        if (!mxIsChar(prhs[1])) {
            mexErrMsgTxt("Second input must be type char.");
        }
    }
    //if ((nrhs == 1)||(strncmp(mode,"4con",mxGetNumberOfElements(prhs[1])))) {
    if ((nrhs == 1)||(*mode == '4')) {
        nzmax = npix*2*ndim;
        //mexPrintf("4con: %d\n",nzmax);
        plhs[0] = mxCreateSparse(npix, npix, nzmax, mxREAL);
        out = mxGetPr(plhs[0]);
        ir = mxGetIr(plhs[0]);
        jc = mxGetJc(plhs[0]);
        k = 0;
        for (i = 0; i < npix; i++) {
            mxAssert(k < nzmax,"Too many nonzeros.");
            jc[i] = k;
            //mexPrintf("Scanning element %d:\n",i);
            for (j = 0; j < ndim; j++) {
                //mexPrintf("  Neighbor at %d:  %d vs. %d.\n",i-offset[j],
                //          (i+npix)/offset[j+1],(i+npix-offset[j])/offset[j+1]);
                if ((i+npix)/offset[j+1] == (i+npix-offset[j])/offset[j+1]) {
                    ir[k] = i-offset[j];
                    out[k] = 1;
                    k++;
                }
                //mexPrintf("  Neighbor at %d:  %d vs. %d.\n",i+offset[j],
                //          (i+npix)/offset[j+1],(i+npix+offset[j])/offset[j+1]);
                if ((i+npix)/offset[j+1] == (i+npix+offset[j])/offset[j+1]) {
                    ir[k] = i+offset[j];
                    out[k] = 1;
                    k++;
                }
            }
        }
        jc[i] = k;
        //} else if (strncmp(mode,"inv2",mxGetNumberOfElements(prhs[1]))) {
    } else if (*mode == 'i') {
        int j2, ji, jp, jm;
        nzmax = npix*2*ndim*(ndim+1);
        //mexPrintf("inv2: %d\n",nzmax);
        plhs[0] = mxCreateSparse(npix, npix, nzmax, mxREAL);
        out = mxGetPr(plhs[0]);
        ir = mxGetIr(plhs[0]);
        jc = mxGetJc(plhs[0]);
        k = 0;
        for (i = 0; i < npix; i++) {
            mxAssert(k < nzmax,"Too many nonzeros.");
            jc[i] = k;
            for (j = 0; j < ndim; j++) {
                ji = i+npix;
                jp = i+npix+offset[j];
                jm = i+npix-offset[j];
                if (ji/offset[j+1] == jp/offset[j+1]) {
                    ir[k] = i+offset[j];
                    out[k] = 1;
                    k++;
                }
                if (ji/offset[j+1] == jm/offset[j+1]) {
                    ir[k] = i-offset[j];
                    out[k] = 1;
                    k++;
                }
                for (j2 = j; j2 < ndim; j2++) {
                    if (jp/offset[j2+1] == (jp+offset[j2])/offset[j2+1]) {
                        ir[k] = i+offset[j]+offset[j2];
                        out[k] = ((j == j2) ? 0.5:HALFSQRT);
                        k++;
                    }
                    if (jm/offset[j2+1] == (jm-offset[j2])/offset[j2+1]) {
                        ir[k] = i-offset[j]-offset[j2];
                        out[k] = ((j == j2) ? 0.5:HALFSQRT);
                        k++;
                    }
                    if (j != j2) {
                        if ((ji/offset[j+1] == jp/offset[j+1])
                                &&(jp/offset[j2+1] == (jp-offset[j2])/offset[j2+1])) {
                            ir[k] = i+offset[j]-offset[j2];
                            out[k] = HALFSQRT;
                            k++;
                        }
                        if ((ji/offset[j+1] == jm/offset[j+1])
                                &&(jm/offset[j2+1] == (jm+offset[j2])/offset[j2+1])) {
                            ir[k] = i-offset[j]+offset[j2];
                            out[k] = HALFSQRT;
                            k++;
                        }
                    }
                }
            }
        }
        jc[i] = k;
        //} else if (strncmp(mode,"edge",mxGetNumberOfElements(prhs[1]))) {
    } else if (*mode == 'e') {
        // Edge image
        bool *edge;
        const int *edim;
        nzmax = npix*2*ndim;
        //mexPrintf("edge: %d\n",nzmax);
        if (nrhs < 3) {
            mexErrMsgTxt("Must provide edge map as third argument.");
        }
        if (!mxIsLogical(prhs[2])) {
            mexErrMsgTxt("Edge map must be logical type.");
        }
        edge = mxGetLogicals(prhs[2]);
        edim = mxGetDimensions(prhs[2]);
        for (i = 0; i < ndim; i++) {
            if (edim[i] != inp[i]) {
                mexErrMsgTxt("Edge map must be same size as image.");
            }
        }
        plhs[0] = mxCreateSparse(npix, npix, nzmax, mxREAL);
        out = mxGetPr(plhs[0]);
        ir = mxGetIr(plhs[0]);
        jc = mxGetJc(plhs[0]);
        k = 0;
        for (i = 0; i < npix; i++) {
            mxAssert(k < nzmax,"Too many nonzeros.");
            jc[i] = k;
            //mexPrintf("Scanning element %d:\n",i);
            for (j = 0; j < ndim; j++) {
                //mexPrintf("  Neighbor at %d:  %d vs. %d.\n",i-offset[j],
                //          (i+npix)/offset[j+1],(i+npix-offset[j])/offset[j+1]);
                if ((i+npix)/offset[j+1] == (i+npix-offset[j])/offset[j+1]) {
                    if (!(edge[i]||edge[i-offset[j]])) {
                        ir[k] = i-offset[j];
                        out[k] = 1;
                        k++;
                    }
                }
                //mexPrintf("  Neighbor at %d:  %d vs. %d.\n",i+offset[j],
                //          (i+npix)/offset[j+1],(i+npix+offset[j])/offset[j+1]);
                if ((i+npix)/offset[j+1] == (i+npix+offset[j])/offset[j+1]) {
                    if (!(edge[i]||edge[i+offset[j]])) {
                        ir[k] = i+offset[j];
                        out[k] = 1;
                        k++;
                    }
                }
            }
        }
        jc[i] = k;
    } else if (*mode == 'd') {
        // deltas
        double *img;
        const int *idim;
        nzmax = npix*2*ndim;
        //mexPrintf("edge: %d\n",nzmax);
        if (nrhs < 3) {
            mexErrMsgTxt("Must provide edge map as third argument.");
        }
        if (!mxIsDouble(prhs[2])||mxIsComplex(prhs[2])) {
            mexErrMsgTxt("Third argument must be grayscale intensities.");
        }
        img = mxGetPr(prhs[2]);
        idim = mxGetDimensions(prhs[2]);
        for (i = 0; i < ndim; i++) {
            if (idim[i] != inp[i]) {
                mexErrMsgTxt("Intensities must be same size as image.");
            }
        }
        plhs[0] = mxCreateSparse(npix, npix, nzmax, mxREAL);
        out = mxGetPr(plhs[0]);
        ir = mxGetIr(plhs[0]);
        jc = mxGetJc(plhs[0]);
        k = 0;
        for (i = 0; i < npix; i++) {
            mxAssert(k < nzmax,"Too many nonzeros.");
            jc[i] = k;
            //mexPrintf("Scanning element %d:\n",i);
            for (j = 0; j < ndim; j++) {
                //mexPrintf("  Neighbor at %d:  %d vs. %d.\n",i-offset[j],
                //          (i+npix)/offset[j+1],(i+npix-offset[j])/offset[j+1]);
                if ((i+npix)/offset[j+1] == (i+npix-offset[j])/offset[j+1]) {
                    ir[k] = i-offset[j];
                    out[k] = 1/ABS(img[i]-img[i-offset[j]]);
                    k++;
                }
                //mexPrintf("  Neighbor at %d:  %d vs. %d.\n",i+offset[j],
                //          (i+npix)/offset[j+1],(i+npix+offset[j])/offset[j+1]);
                if ((i+npix)/offset[j+1] == (i+npix+offset[j])/offset[j+1]) {
                    ir[k] = i+offset[j];
                    out[k] = 1/ABS(img[i]-img[i+offset[j]]);
                    k++;
                }
            }
        }
        jc[i] = k;
    } else {
        mexErrMsgTxt("Unknown mode.");
    }

    // free memory
    mxFree(offset);
}
Ejemplo n.º 28
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;
			}
		}
	}
}
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.º 30
0
/* here comes the main function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    /* default settings */
    /* connectivity pattern: 2 */
    const double DEF_clconn = 2.0;

    /* threshold 1 (consider also single voxel clusters) */
    const double DEF_kthr   = 1.0;

    /* setting pointers (for argument read-out) */
    const double *clconn = NULL;
    const double *kthr   = NULL;

    /* settings (internal) */
    /* max directions */
    unsigned int md = 2;

    /* cluster threshold */
    unsigned int kthrl = 1;



    /* sizes and position */
    const int *dim = NULL;
    int idim[3] = {1, 1, 1};
    int tdim[3] = {1, 1, 1};

    /* offset (must be variable, as copy might not require additional slices) */
    unsigned int toff[3] = {1, 1, 1};

    /* dimX, dimY, dimZ, dimXY, next position */
    unsigned int dx = 0, dy = 0, dz = 0, dxy = 0, dxyz = 0, np = 0;

    /* data pointers */
    /* (enlarged) copy */
    unsigned char *copy = NULL;

    /* list of cluster voxels */
    unsigned int clvoxcnt;
    unsigned int clnxtvox;
    signed int *clvox = NULL;

    /* list of cluster sizes and total number of clustered voxels */
    unsigned int mxclnum = 0;
    unsigned int clnum = 0;
    unsigned int *clsiz = NULL;
    unsigned int cltvox = 0, cltvox2 = 0, cltvox3 = 0;

    /* clustered volume (internal) */
    unsigned int *clvol = NULL;

    /* direction increments (as index differences) */
    signed int dlxyz[26] =
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    /* next positions (signed!) */
    signed int nextp = 0, nextpi = 0;

    /* counters */
    signed char dc = 0;
    unsigned int cx = 0, cy = 0, cz = 0;

    /* output pointer(s) */
    mxArray *ma = NULL;
    double *op = NULL, *sop = NULL;

    /* variable output text */
    /* char vstr[256]; */



    /* code starts here */



    /* nr. of arguments check */
    if ((nrhs < 1) ||
        (nlhs > 4))
        mexErrMsgTxt("Bad number of input/output arguments.");

    /* first argument class and size check */
    if (!mxIsLogical(prhs[0]) ||
        (mxGetNumberOfElements(prhs[0]) < 8) ||
        (mxGetNumberOfDimensions(prhs[0]) > 3))
        mexErrMsgTxt("Invalid argument type or dimension.");

    /* check connectivity flag */
    if ((nrhs < 2) ||
        !mxIsDouble(prhs[1]) ||
        (mxGetNumberOfElements(prhs[1]) != 1))
	clconn = &DEF_clconn;
    else {
	clconn = (const double*) mxGetPr(prhs[1]);
	if (mxIsNaN(*clconn) ||
	    mxIsInf(*clconn) ||
	   ((*clconn) < 1.0) ||
	   ((*clconn) > 5.0))
	    clconn = &DEF_clconn;
    }

    /* check threshold */
    if ((nrhs < 3) ||
        !mxIsDouble(prhs[2]) ||
        (mxGetNumberOfElements(prhs[2]) != 1))
        kthr = &DEF_kthr;
    else {
        kthr = (const double*) mxGetPr(prhs[2]);
        if (mxIsNaN(*kthr) ||
            mxIsInf(*kthr) ||
           ((*kthr) < 1.0) ||
           ((*kthr) > (0.5 * mxGetNumberOfElements(prhs[0]))))
            kthr = &DEF_kthr;
    }
    kthrl = (unsigned int) *kthr;

    /* get & check argument content */
    dim = mxGetDimensions(prhs[0]);
    idim[0] = dim[0];
    idim[1] = dim[1];
    if (mxGetNumberOfDimensions(prhs[0]) > 2)
        idim[2] = dim[2];
    dx = idim[0];
    dy = idim[1];
    dz = idim[2];
    dxy = dx * dy;
    dxyz = dxy * dz;
    mxclnum = (unsigned int) (((double) (dxyz + 3)) / 4.0);

    /* set connectivity flag -> max directions (opposite direction later) */
    /* face connectivity -> three main directions */
    if ((*clconn >= 1.0) && (*clconn < 1.5))
        md = 3;

    /* edge connectivity -> add 6 edge diagonals */
    else if ((*clconn >= 1.5) && (*clconn < 2.5))
        md = 9;

    /* vertex connectivity -> add 4 3D diagonals */
    else if ((*clconn >= 2.5) && (*clconn < 3.5))
        md = 13;
    /* otherwise, leave at 2, we stay "in-plane" */

    /* reserve space for next cluster list and cluster sizes */
    clvox = (signed int *) mxCalloc(dxyz, sizeof(signed int));
    if (clvox == NULL)
	mexErrMsgTxt("Error allocating next cluster voxel list.");
    clsiz = (unsigned int *) mxCalloc(mxclnum, sizeof(signed int));
    if (clsiz == NULL) {
        mxFree(clvox);
	mexErrMsgTxt("Error allocating next cluster voxel list.");
    }

    /* increase numbers accordingly */
    if (idim[0] > 1)
        dx += 2;
    else
        toff[0] = 0;
    if (idim[1] > 1)
        dy += 2;
    else
        toff[1] = 0;
    if (idim[2] > 1)
        dz += 2;
    else
        toff[2] = 0;

    /* compute new plane/vol numel */
    dxy = dx * dy;
    dxyz = dxy * dz;

    /* reserve space for clustered volume (if needed) */
    if (nlhs > 1) {
        clvol = (unsigned int *) mxCalloc(dxyz, sizeof(unsigned int));
        if (clvol == NULL) {
            mxFree(clsiz);
            mxFree(clvox);
            mexErrMsgTxt("Error allocating clustered volume.");
        }
    }

    /* set temp dim array */
    tdim[0] = dx;
    tdim[1] = dy;
    tdim[2] = dz;

    /* fill direction increment array */
    np = 0;
    for (dc = 0; dc < md; ++dc) {
        if (((idim[0] > 1) ||
             (dlx[dc] == 0)) &&
            ((idim[1] > 1) ||
             (dly[dc] == 0)) &&
            (((idim[2] > 1) &&
	      (*clconn < 3.5)) ||
             (dlz[dc] == 0))) {
            dlxyz[np] = dlx[dc] + dly[dc] * dx + dlz[dc] * dxy;
            dlxyz[np+1] = -dlxyz[np];
            np += 2;
        }
    }
    if ((*clconn >= 4.5) &&
        (idim[0] > 1) &&
        (idim[1] > 1)) {
        for (dc = 3; dc < 5; ++dc) {
            dlxyz[np] = dlx[dc] + dly[dc] * dx + dlz[dc] * dxy;
            dlxyz[np+1] = -dlxyz[np];
            np += 2;
        }
    }

    /* re-set */
    md = np - 1;

    /* create temp. copy array */
    copy = (unsigned char *) mxCalloc(dxyz, sizeof(unsigned char));
    if (copy == NULL) {
        mxFree(clsiz);
        mxFree(clvox);
        mexErrMsgTxt("Error allocating temporary memory");
    }

    /* copy into temporary array */
    ff_copy_intopart(idim[0], idim[1], idim[2], (unsigned char *) mxGetPr(prhs[0]), tdim, copy, toff);



    /* preparations complete, now we can "search"... */



    /* iterate while new points found */
    for (np = 0; np < dxyz; ++np) {

	/* check voxel */
        if (copy[np] == 1) {

            /* start new cluster */
            clvoxcnt = 1;
            clvox[0] = np;

            /* remove from search volume */
            copy[np] = 0;

            /* continue until no more neighbors found */
            for (clnxtvox = 0; clnxtvox < clvoxcnt; ++clnxtvox) {

                /* check neighbors */
                nextp = clvox[clnxtvox];
                for (dc = md;  dc >= 0; --dc) {

                    /* check voxel with increment */
                    nextpi = nextp + dlxyz[dc];
                    if (copy[nextpi] == 1) {

                            /* equally remove from search volume */
                            copy[nextpi] = 0;

                            /* and add to list */
                            clvox[clvoxcnt++] = nextpi;
                    }
                }
            }

            /* rest of code only if surpasses threshold */
            if (clvoxcnt >= kthrl) {

                /* write to list of sizes and increase cluster number count */
                clsiz[clnum++] = clvoxcnt;
                cltvox += clvoxcnt;

                /* write to output volume (if needed) */
                if (nlhs > 1) {
                    for (nextp = clvoxcnt - 1; nextp >= 0; --nextp)
                        clvol[clvox[nextp]] = clnum;
                }
            }
        }
    }

    /* we're done with this */
    mxFree(copy);

    /* create output argument #1 */
    CREATE_MxN(plhs[0], 1, clnum);
    if (plhs[0] == NULL) {
        if (clvol != NULL)
            mxFree(clvol);
        mxFree(clsiz);
        mxFree(clvox);
        mexErrMsgTxt("Error creating output argument cs.");
    }

    /* if requested create other outputs first */
    if (nlhs > 1) {
        plhs[1] = mxCreateNumericArray(3, idim, mxUINT32_CLASS, mxREAL);
        if (plhs[1] == NULL) {
            mxDestroyArray(plhs[0]);
            mxFree(clvol);
            mxFree(clsiz);
            mxFree(clvox);
            mexErrMsgTxt("Error creating output argument cv.");
        }
    }

    /* if requested create other outputs first */
    if (nlhs > 2) {
        CREATE_MxN(plhs[2], cltvox, 4);
        if (plhs[2] == NULL) {
            mxDestroyArray(plhs[1]);
            mxDestroyArray(plhs[0]);
            mxFree(clvol);
            mxFree(clsiz);
            mxFree(clvox);
            mexErrMsgTxt("Error creating output argument l.");
        }
    }

    /* if requested create other outputs first */
    if (nlhs > 3) {
        plhs[3] = mxCreateCellMatrix(1, clnum);
        if (plhs[3] == NULL) {
            mxDestroyArray(plhs[2]);
            mxDestroyArray(plhs[1]);
            mxDestroyArray(plhs[0]);
            mxFree(clvol);
            mxFree(clsiz);
            mxFree(clvox);
            mexErrMsgTxt("Error creating output argument c.");
        }
        /* put numeric array into each cell */
        for (nextp = 0; nextp < clnum; ++nextp) {
            CREATE_MxN(ma, clsiz[nextp], 3);
            if (ma == NULL) {
                mxDestroyArray(plhs[3]);
                mxDestroyArray(plhs[2]);
                mxDestroyArray(plhs[1]);
                mxDestroyArray(plhs[0]);
                mxFree(clvol);
                mxFree(clsiz);
                mxFree(clvox);
                mexErrMsgTxt("Error creating output cell contents in argument c.");
            }
            mxSetCell(plhs[3], nextp, ma);
        }
    }

    /* copy cluster sizes into output */
    op = (double *) mxGetPr(plhs[0]);
    for (nextp = 0; nextp < clnum; ++nextp)
        *op++ = (double) clsiz[nextp];

    /* copy volume to output */
    if (nlhs > 1) {
        ff_copy_frompart(dx, dy, clvol, idim, (unsigned int*) mxGetData(plhs[1]), toff);
        mxFree(clvol);
        clvol = (unsigned int *) mxGetPr(plhs[1]);
    }

    /* create list of voxels */
    if (nlhs > 2) {

        /* get output pointer */
        op = (double *) mxGetPr(plhs[2]);

        /* 2/3 * total count for fast indexing */
        cltvox2 = 2 * cltvox;
        cltvox3 = 3 * cltvox;

        /* if required re-init counter */
        if (nlhs > 3) {
            for (nextp = clnum - 1; nextp >= 0; --nextp)
                clvox[nextp] = 0;
        }

        dx = idim[0];
        dy = idim[1];
        dz = idim[2];
        dxy = dx * dy;
        for (cz = 0; cz < dz; ++cz) {
            dxyz = dxy * cz;
            for (cy = 0; cy < dy; ++cy) {
                np = dxyz + cy * dx;
                for (cx = 0; cx < dx; ++cx) {
                    clnum = *clvol++;
                    if (clnum > 0) {
                        op[cltvox3] = (double) clnum;
                        op[cltvox2] = (double) (cz + 1);
                        op[cltvox]  = (double) (cy + 1);
                        *op++ = (double) (cx + 1);
                        if (nlhs > 3) {
                            --clnum;
                            sop = (double *) mxGetPr(mxGetCell(plhs[3], clnum));
                            sop[2 * clsiz[clnum] + clvox[clnum]] = (double) (cz + 1);
                            sop[clsiz[clnum] + clvox[clnum]] = (double) (cy + 1);
                            sop[clvox[clnum]++] = (double) (cx + 1);
                        }
                    }
                }
            }
        }
    }

    /* free other temp arrays */
    mxFree(clsiz);
    mxFree(clvox);

}