Ejemplo n.º 1
0
/**
 * @brief This file implements an interface to add a Factor to an opengm model in MatLab.
 *
 * This routine accepts a function id and a subset of variables and connects them to a new factor of the model.
 *
 * @param[in] nlhs number of output arguments expected from MatLab.
 * (needs to be 1).
 * @param[out] plhs pointer to the mxArrays containing the results.
 * plhs[0] objective value of the labeling
 * @param[in] nrhs number of input arguments provided from MatLab.
 * (needs to be 2)
 * @param[in] prhs pointer to the mxArrays containing the input data provided by
 * matlab.
 * prhs[0] needs to contain the handle for the model.
 * prhs[1] labeling
 *  //// prhs[2] needs to contain the vector representing the subset of variables.
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    //check if data is in correct format
    if(nrhs != 2) {
        mexErrMsgTxt("Wrong number of input variables specified (two needed)\n");
    }
    if(nlhs != 1) {
        mexErrMsgTxt("Wrong number of output variables specified (one needed)\n");
    }

    // get model out of handle
    typedef opengm::interface::MatlabModelType::GmType GmType;
    GmType& gm = opengm::interface::handle<GmType>::getObject(prhs[0]);

    // get labeling
    if(mxIsNumeric(prhs[1])) {
        if( ((mxGetM(prhs[1]) * mxGetN(prhs[1]) != gm.numberOfVariables()))) {
            mexErrMsgTxt("labeling has wrong size!");
        }
        //std::vector<GmType::ValueType> labeling;
        double* m_labeling = reinterpret_cast<double*>(mxGetData(prhs[1]) );
        //for (size_t i=0; i<gm.numberOfVariables(); ++i)
        //   labeling[i] =  m_labeling[i];

        GmType::ValueType value = gm.evaluate(m_labeling);
        plhs[0] = mxCreateNumericMatrix(1, 1, mxDOUBLE_CLASS, mxREAL);
        reinterpret_cast<double*>(mxGetData(plhs[0]))[0] = static_cast<double>(value);
    } else {
        mexErrMsgTxt("Unsupported dataformat for subset of variables!");
    }
}
Ejemplo n.º 2
0
static double scalarcheck(
  const mxArray *matval,  /* The input array to check. */
  const int k,            /* Argument number, for debugging. */
  const int mytype        /* 0: numeric, 1: for usb_dev_handle. */
) {
	int mrows, ncols;

	if(mytype == 0) {
		if(!mxIsNumeric(matval)) {
			mexErrMsgIdAndTxt("USB:writestring","Argument %d must be numeric",k+1);
		}
	} else {
		if(!mxIsUint64(matval)) {
			mexErrMsgIdAndTxt("USB:writestring","Argument %d must be Uint64",k+1);
		}
	}
	if(mxIsComplex(matval)) {
		mexErrMsgIdAndTxt("USB:writestring","Argument %d must be noncomplex",k+1);
	}
	mrows = mxGetM(matval);
	ncols = mxGetN(matval);
	if(mrows!=1 || ncols != 1) {
			mexErrMsgIdAndTxt("USB:writestring","Argument %d must be scalar",k+1);
	}
	return mxGetScalar(matval);
}
Ejemplo n.º 3
0
// *********************************************************************
// *                              GetTau                               *
// *********************************************************************
// value = classifier_get_tau (id)
static void classifier_get_tau (int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs)
{
    // Validate arguments
    if (nrhs != 1) {
        mexErrMsgTxt("Command requires one input argument!");
    }

    if (mxGetNumberOfElements(prhs[0]) != 1 || !mxIsNumeric(prhs[0])) {
        mexErrMsgTxt("First input argument needs to be a numeric ID!");
    }

    if (nlhs != 1) {
        mexErrMsgTxt("Command requires one output argument!");
    }

    // Get handle ID
    int id = static_cast<int>(mxGetScalar(prhs[0]));

    // Try to find the classifier
    auto iterator = objects.find(id);
    if (iterator == objects.end()) {
        mexErrMsgTxt("Invalid handle ID!");
    }
    auto &classifier = iterator->second;

    // Return value
    plhs[0] = mxCreateDoubleScalar(classifier->getTau());
}
Ejemplo n.º 4
0
void vel2mom_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    int nd;
    const int *dm;
    int rtype = 0;
    static double param[] = {1.0, 1.0, 1.0, 0.0, 0.0};

    if (nrhs!=2 || nlhs>1)
        mexErrMsgTxt("Incorrect usage");
    if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]))
        mexErrMsgTxt("Data must be numeric, real, full and double");
    nd = mxGetNumberOfDimensions(prhs[0]);
    if (nd!=3) mexErrMsgTxt("Wrong number of dimensions.");
    dm = mxGetDimensions(prhs[0]);
    if (dm[2]!=2)
        mexErrMsgTxt("3rd dimension must be 2.");

    if (mxGetNumberOfElements(prhs[2]) >6)
        mexErrMsgTxt("Third argument should contain rtype, vox1, vox2, param1, param2, and param3.");
    if (mxGetNumberOfElements(prhs[2]) >=1) rtype    = (int)mxGetPr(prhs[2])[0];
    if (mxGetNumberOfElements(prhs[2]) >=2) param[0] = 1/mxGetPr(prhs[2])[1];
    if (mxGetNumberOfElements(prhs[2]) >=3) param[1] = 1/mxGetPr(prhs[2])[2];
    if (mxGetNumberOfElements(prhs[2]) >=4) param[2] = mxGetPr(prhs[2])[3];
    if (mxGetNumberOfElements(prhs[2]) >=5) param[3] = mxGetPr(prhs[2])[4];
    if (mxGetNumberOfElements(prhs[2]) >=6) param[4] = mxGetPr(prhs[2])[5];

    plhs[0] = mxCreateNumericArray(nd,dm, mxDOUBLE_CLASS, mxREAL);

    if (rtype==1)
        LtLf_me((int *)dm, mxGetPr(prhs[0]), param, mxGetPr(plhs[0]));
    else if (rtype==2)
        LtLf_be((int *)dm, mxGetPr(prhs[0]), param, mxGetPr(plhs[0]));
    else
        LtLf_le((int *)dm, mxGetPr(prhs[0]), param, mxGetPr(plhs[0]));
}
Ejemplo n.º 5
0
/*
 *  getData:  Gets data from a Matlab argument.
 *  Inputs: 
 *      const mxArray **prhs: Right hand side argument with RGB image
 *      (image8 *) Pointer to the image structure.
 */
void getData( const mxArray **prhs, image8 *im )
{ 
    uint8      *pr;
    int         index, number_of_dimensions, total_elements; 
    const int   *ldims;
    
	if (mxIsNumeric(*prhs) == 0) 
		mexErrMsgTxt("Not numbers...\n");
    
    for (index=0; index<NDIMS; index++)
        im->dims[index]=0;
    
    total_elements = mxGetNumberOfElements(*prhs);
    number_of_dimensions = mxGetNumberOfDimensions(*prhs);
    ldims = mxGetDimensions(*prhs);
    for (index=0; index<number_of_dimensions; index++)
        im->dims[index] = ldims[index];
    
    pr = (uint8 *)mxGetData(*prhs);
    
    if( number_of_dimensions > NDIMS )
        mexErrMsgTxt("This input exceeds proper dimensions...\n");
    
    //Allocated the space
    if ( (im->im = (uint8 *) malloc(sizeof(uint8) * total_elements)) == NULL )
        mexErrMsgTxt("im malloc failed...\n");
    
    //Get the image
	memcpy(im->im, pr, sizeof(uint8) * total_elements);

    return;
}
Ejemplo n.º 6
0
/* Convert the attribute and FLA_Obj arguments */
void FLA_M2C_ConvertArgs(int nrhs, const mxArray *prhs[], int nint, 
			 int attr[], FLA_Obj obj[]) {
  char err[200];
  int i, j;

  /* First convert all the attributes */
  /* Check if the argument is a string before calling the conversion function */
  for (i=0; i<nint; i++) {
    if (mxIsChar(prhs[i])) {
      attr[i] = FLA_M2C_ConvertAttribute(prhs[i]);
    }
    else {
      sprintf(err, "The %dth argument must be a FLAME attribute string.", i+1);
      mexErrMsgTxt(err);
    }
  }

  /* The remaining arguments are converted to FLA_Obj */
  /* Check if the argument is numeric before calling the conversion function */
  for (i=i; i<nrhs; i++) {
    if (mxIsNumeric(prhs[i])) {
      obj[i-nint] = FLA_M2C_ConvertMxArray(prhs[i]);
    }
    else {
      sprintf(err, "The %dth argument must be numeric.", i+1);
      mexErrMsgTxt(err);
    }
  }

} 
mxArray* getSource(biEntry* obj)
{
   if (obj->var == NULL || mxIsNumeric(obj->var))
      return mxCreateString("numeric");
   else
      return obj->var;
}
Ejemplo n.º 8
0
/* Convert Matlab array to C FLAME object */
FLA_Obj FLA_M2C_ConvertMxArray(const mxArray *mobj) {
  int type;
  FLA_Obj fobj;

  if (!mxIsNumeric(mobj)) {
    mexErrMsgTxt("Numeric data expected.");
  }
  else {
    /* Determine data type of the matlab array. */
    if (mxIsDouble(mobj))
      if (mxIsComplex(mobj))
	type = FLA_DOUBLE_COMPLEX;
      else
	type = FLA_DOUBLE;
    else if (mxIsSingle(mobj))
      if (mxIsComplex(mobj))
	type = FLA_COMPLEX;
      else
	type = FLA_FLOAT;
    else if (mxIsInt32(mobj))
      type = FLA_INT;
    else
      mexErrMsgTxt("Data type not supported.");

    fobj.datatype = type;
    fobj.m = mxGetM(mobj);
    fobj.n = mxGetN(mobj);
    fobj.buffer = mxGetPr(mobj);
    fobj.ldim = fobj.m;

    return fobj;
  }

}
Ejemplo n.º 9
0
/* tz_writetifstack(stack, filepath)
 *
 * Write tif stack. There is no output.
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  if (nrhs != 2) {
    mexErrMsgTxt("The function takes 2 argument exactly.");
  }

  if (!mxIsNumeric(prhs[0])) {
    mexErrMsgTxt("The first argument must be a numeric array.");
  }

  if (!mxIsUint8(prhs[0]) && !mxIsUint16(prhs[0])) {
    mexErrMsgTxt("The first argument must be a uint8 or uint16 array.");
  }

  if (!mxIsChar(prhs[1])) {
    mexErrMsgTxt("The second argument must be a string.");
  }
  
  char *file_path = mxArrayToString(prhs[1]);
  Array_Link *a = MxArray_To_Stack(prhs[0]);
  Stack *stack = Get_Stack_At(a);
  if (stack->text == NULL) {
    stack->text = "\0";
  }
  Write_Stack(file_path, stack);
  Delete_Array_Link(a);
}
Ejemplo n.º 10
0
void interleaveMatrix(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  const mxArray *inArray;
  if(nrhs != 1 || !prhs || !(inArray = *prhs) || !mxIsNumeric(inArray) || mxIsSparse(inArray)) 
    mexErrMsgTxt("Input matrix must be a non-sparse numeric array!");
  //if(nlhs < 1) mexErrMsgTxt("One output argument required.");

  mxArray * & outArray = plhs[0];
  
  const int m = mxGetM(inArray), 
            n = mxGetN(inArray);  
  const int dims[] = { 1, m*n };
  
  outArray = mxCreateNumericArray(2, dims, mxGetClassID(inArray), mxREAL);
  const unsigned elem_size = mxGetElementSize(inArray);
  /*  GenericMatrix 
    in(mxGetData(inArray), elem_size, m, n), 
    out(mxGetData(outArray), elem_size, 1, m*n);
  for (int i = 0; i < m; ++i)
    for (int j = 0; j < n; j++) 
    out[0][i*n + j] = static_cast<void *>( in[i][j] );*/

  // NB: you can just do a memcpy since all matrices are stored in column-major order anyway..
  ::memcpy(mxGetData(outArray), mxGetData(inArray), elem_size*m*n);
}
Ejemplo n.º 11
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

  int err;
  lo_server s;

  if (nrhs != 1) {
    mexErrMsgTxt("Please specify one arguement, port.");
    return;
  }
  if (nlhs > 1) {
    mexErrMsgTxt("Too many output arguments.");
    return;
  }

  if(! mxIsNumeric(prhs[0])) {
    mexErrMsgTxt("Expecting a numeric scalar in the first argument.");
    return;
  }

  sprintf(port, "%d", (int)(mxGetScalar(prhs[0])));
  s = lo_server_new(port, NULL);  // No error handler...

  if(! s) {
    mexErrMsgTxt("Error creating server.");
    return;
  }

  sprintf(maddr, "osc_server:%x", (void*) s);
  plhs[0] = mxCreateString(maddr);

}
Ejemplo n.º 12
0
/* 此函數為和 MATLAB 溝通的主要函數 */
void mexFunction(
	int nlhs,	mxArray *plhs[],
	int nrhs, const mxArray *prhs[]) {
	double	*out, *mat1, *mat2, squareSum;
	int m, p, n, p2, i, j, k;

	/* 檢查輸出變數個數是否為2、輸入變數個數是否為1,其中	  */
	/* nrhs = no. of right-hand-side arguments(輸入變數個數)*/
	/* nlhs = no. of  left-hand-side arguments(輸出變數個數)*/
	if (nrhs!=2)
		mexErrMsgTxt("PAIRDIST requires two input arguments.");

	/* 檢查維度是否符合要求 */
	p  = mxGetM(MAT1);
	m  = mxGetN(MAT1);
	p2  = mxGetM(MAT2);
	n = mxGetN(MAT2);
	if (p != p2)
		mexErrMsgTxt("Matrix sizes mismatch!");

	/* 檢查輸入變數資料型態是否符合要求 */
	if (!mxIsNumeric(MAT1) || mxIsSparse(MAT1)  || !mxIsDouble(MAT1))
		mexErrMsgTxt("Input 1 is not a full numerical array!");
	if (!mxIsNumeric(MAT2) || mxIsSparse(MAT2)  || !mxIsDouble(MAT2))
		mexErrMsgTxt("Input 2 is not a full numerical array!");

	/* 配置記憶體給輸出變數 */
	OUT = mxCreateDoubleMatrix(m, n, mxREAL);

	/* 取得輸入和輸出變數的實部指標 */
	out = mxGetPr(OUT);
	mat1 = mxGetPr(MAT1);
	mat2 = mxGetPr(MAT2);

	/* 實際計算部份 */
	/* MAT1(i+1, j+1) 的值是 mat1[j*m+i] */
	/* MAT2(i+1, j+1) 的值是 mat2[j*n+i] */
	/*  OUT(i+1, j+1) 的值是  out[j*m+i] */

	for (i=0; i<m; i++)
		for (j=0; j<n; j++) {
			squareSum = 0;
			for (k=0; k<p; k++)
				squareSum += pow(mat1[i*p+k]-mat2[j*p+k], 2.0);
			out[j*m+i] = sqrt(squareSum);
		}
}
Ejemplo n.º 13
0
static void newProposal( MEX_ARGS ) {
    if( nlhs == 0 ) {
        mexErrMsgTxt("newProposal expected one return argument");
        return;
    }
    // Create an empty unary
    ProposalSettings prop_settings;
    prop_settings.unaries.clear();
    
    // Add all settings
    for ( int i=0; i<nrhs; i++ ) {
        std::string c = toString( prhs[i] );
        
        // Process the command
        if (c == "max_iou") {
            if( i+1>=nrhs || !mxIsNumeric(prhs[i+1]) )
                mexErrMsgTxt("max_iou numeric argument required");
            prop_settings.max_iou = mxGetScalar(prhs[i+1]);
            i++;
        }
        else if (c == "seed") {
            if( i+1>=nrhs || !mxIsChar(prhs[i+1]) )
                mexErrMsgTxt("seed string argument required");
            prop_settings.foreground_seeds = createSeed( toString( prhs[i+1] ) );
            i++;
        }
        else if (c == "unary") {
            if( i+4 >= nrhs || !mxIsNumeric(prhs[i+1]) || !mxIsNumeric(prhs[i+2]) || !mxIsChar(prhs[i+3]) || !mxIsChar(prhs[i+4]) )
                mexErrMsgTxt("unary N_S:int N_T:int fg_unary:string bg_unary:string [min_size:float max_side:float]");
            const int N_S = mxGetScalar(prhs[i+1]), N_T = mxGetScalar(prhs[i+2]);
            std::string fg_unary = toString( prhs[i+3] ), bg_unary = toString( prhs[i+4] );
            float min_size = 0.0, max_size=0.75;
            if( i+6 <= nrhs && mxIsNumeric(prhs[i+5]) && mxIsNumeric(prhs[i+5]) ) {
                min_size = mxGetScalar( prhs[i+5] );
                max_size = mxGetScalar( prhs[i+6] );
                i += 2;
            }
            prop_settings.unaries.push_back( ProposalSettings::UnarySettings( N_S, N_T, createUnaryFromString( fg_unary ), createUnaryFromString( bg_unary ), min_size, max_size ) );
            i+=4;
        }
        else {
            mexErrMsgTxt(("Setting '"+c+"' not found").c_str());
        }
    }
    plhs[0] = ptr2Mat( std::make_shared<Proposal>( prop_settings ) );
}
Ejemplo n.º 14
0
float64_t CMatlabInterface::get_real()
{
	const mxArray* f=get_arg_increment();
	if (!f || !mxIsNumeric(f) || mxGetN(f)!=1 || mxGetM(f)!=1)
		SG_ERROR("Expected Scalar Float as argument %d\n", m_rhs_counter);

	return mxGetScalar(f);
}
Ejemplo n.º 15
0
// [ label, confidence ] = classifier_predict (id, features)
static void classifier_predict (int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs)
{
    // Validate arguments
    if (nrhs != 2) {
        mexErrMsgTxt("Command requires two input arguments!");
    }

    if (mxGetNumberOfElements(prhs[0]) != 1 || !mxIsNumeric(prhs[0])) {
        mexErrMsgTxt("First input argument needs to be a numeric ID!");
    }

    if (!mxIsSingle(prhs[1]) && !mxIsDouble(prhs[1])) {
        mexErrMsgTxt("Second input argument needs to be a single or double vector/matrix!");
    }

    // Get handle ID
    int id = static_cast<int>(mxGetScalar(prhs[0]));

    // Try to find the classifier
    auto iterator = objects.find(id);
    if (iterator == objects.end()) {
        mexErrMsgTxt("Invalid handle ID!");
    }
    auto &classifier = iterator->second;

    // Get feature matrix/vector: DxN matrix for N samples
    unsigned int numFeatures = static_cast<unsigned int>(mxGetM(prhs[1])); // rows = feature dimension
    unsigned int numSamples = static_cast<unsigned int>(mxGetN(prhs[1])); // columns = number of samples
    unsigned int numClasses = classifier->getNumClasses();

    // Initialize output
    if (nlhs >= 1) {
        plhs[0] = mxCreateNumericMatrix(1, numSamples, mxSINGLE_CLASS, mxREAL);
    }
    if (nlhs >= 2) {
        plhs[1] = mxCreateNumericMatrix(numClasses, numSamples, mxSINGLE_CLASS, mxREAL);
    }

    // Process all samples
    float *labelsPtr = (nlhs >= 1) ? static_cast<float *>(mxGetData(plhs[0])) : 0;
    float *scoresPtr = (nlhs >= 2) ? static_cast<float *>(mxGetData(plhs[1])) : 0;

    if (mxIsDouble(prhs[1])) {
        // Double-precision features
        __classifier_predict<double>(classifier,
            static_cast<const double *>(mxGetData(prhs[1])),
            numClasses, numSamples, numFeatures,
            labelsPtr,
            scoresPtr);
    } else {
        // Single-precision features
        __classifier_predict<float>(classifier,
            static_cast<const float *>(mxGetData(prhs[1])),
            numClasses, numSamples, numFeatures,
            labelsPtr,
            scoresPtr);
    }
}
Ejemplo n.º 16
0
Archivo: S4mex.c Proyecto: soamaven/S4
static void complex_check(int arg, const mxArray *prhs[], const char *argname, double *ret){
	if(!mxIsNumeric(prhs[arg]) || !mxIsScalar(prhs[arg])){
		mexErrMsgIdAndTxt("S4:invalidInput", "Expected complex number.");
	}
	ret[0] = *(mxGetPr(prhs[arg]));
	if(mxIsComplex(prhs[arg])){
		ret[1] = *(mxGetPi(prhs[arg]));
	}
}
Ejemplo n.º 17
0
void fmg_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    const int *dm;
    int        cyc=1, nit=1, rtype=2;
    double     *A, *b, *x, *scratch;
    static double param[] = {1.0, 1.0, 1.0, 1.0, 0.0};

    if (nrhs!=3 || nlhs>1)
        mexErrMsgTxt("Incorrect usage");
    if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]))
        mexErrMsgTxt("Data must be numeric, real, full and double");
    if (mxGetNumberOfDimensions(prhs[0])!=3) mexErrMsgTxt("Wrong number of dimensions.");

    if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]))
        mexErrMsgTxt("Data must be numeric, real, full and double");
    if (mxGetNumberOfDimensions(prhs[1])!=3) mexErrMsgTxt("Wrong number of dimensions.");
    dm = mxGetDimensions(prhs[1]);

    if (mxGetDimensions(prhs[0])[0] != dm[0])
        mexErrMsgTxt("Incompatible 1st dimension.");
    if (mxGetDimensions(prhs[0])[1] != dm[1])
        mexErrMsgTxt("Incompatible 2nd dimension.");
    if (mxGetDimensions(prhs[0])[2] != dm[2])
        mexErrMsgTxt("Incompatible 3rd dimension.");

    if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2]))
        mexErrMsgTxt("Data must be numeric, real, full and double");
    if (mxGetNumberOfElements(prhs[2]) != 4)
        mexErrMsgTxt("Third argument should contain rtype, lambda, ncycles and relax-its.");

    rtype    = (int)(mxGetPr(prhs[2])[0]);
    param[3] = mxGetPr(prhs[2])[1];
    cyc      = (int)(mxGetPr(prhs[2])[2]);
    nit      = (int)(mxGetPr(prhs[2])[3]);

    plhs[0] = mxCreateNumericArray(3,dm, mxDOUBLE_CLASS, mxREAL);

    A       = (double *)mxGetPr(prhs[0]);
    b       = (double *)mxGetPr(prhs[1]);
    x       = (double *)mxGetPr(plhs[0]);
    scratch = (double *)mxCalloc(fmg_scratchsize((int *)dm),sizeof(double));
    fmg((int *)dm, A, b, rtype, param, cyc, nit, x, scratch);
    mxFree((void *)scratch);
}
Ejemplo n.º 18
0
/*
 * sample file that shows how to transform an array of structs
 * containing (id, handle) pairs to a callback list and return the
 * pointer to the data. the callback list can thus be passed to the
 * second file in this example (exec_callbacks.cpp).
 *
 * The passed matlab functions must not have any argument as this example here
 * doesn't take care of those arguments.
 */
void
mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	if (nrhs != 1)
		mexErrMsgTxt("Function requires exactly one argument.\n");
	if (nlhs != 1)
		mexErrMsgTxt("Function returns exactly one value.\n");

	if (!mxIsStruct(prhs[0]))
		mexErrMsgTxt("Function requires a structure array as argument\n");

	int nfields = mxGetNumberOfFields(prhs[0]);
	mwSize nstructs = mxGetNumberOfElements(prhs[0]);

	std::vector<callback*> *cb_list = new std::vector<callback*>();
	// parse each struct
	for (mwIndex i = 0; i < nstructs; i++) {
		bool id_found = false;
		bool fn_found = false;

		callback *cb = new callback();
		for (int j = 0; j < nfields; j++) {
			mxArray *field = mxGetFieldByNumber(prhs[0], i, j);
			if (!field) {
				mexWarnMsgTxt("Invalid structure found\n");
				continue;
			}

			const char *fname = mxGetFieldNameByNumber(prhs[0], j);
			if (!strncmp(fname, "id", sizeof("id"))) {
				if (!mxIsNumeric(field) || mxGetNumberOfElements(field) != 1) {
					mexWarnMsgTxt("Invalid id (must be numeric scalar).\n");
					continue;
				}
				id_found = true;
				cb->id = (int)mxGetScalar(field);
			}
			else if (!strncmp(fname, "handle", sizeof("handle"))) {
				if (!mxIsClass(field, "function_handle")) {
					mexWarnMsgTxt("Invalid handle (must be function_handle).\n");
					continue;
				}
				fn_found = true;

				cb->fn = field;
			}
		}

		if (!id_found || !fn_found)
			delete cb;
		else
			cb_list->push_back(cb);
	}
	// return the list
	plhs[0] = create_mex_obj(cb_list);
}
Ejemplo n.º 19
0
VecD MatlabArrayToVector(const mxArray* p) {
	CHECK(mxIsNumeric(p));
	VecD v(mxGetM(p) * mxGetN(p));
	const double* pd = mxGetPr(p);
	CHECK(pd);
	for (int i = 0; i < v.Size(); i++) {
		v[i] = *pd++;
	}
	return v;
}
Ejemplo n.º 20
0
/**
 * @brief This file implements an interface to add a Factor to an opengm model in MatLab.
 *
 * This routine accepts a function id and a subset of variables and connects them to a new factor of the model.
 *
 * @param[in] nlhs number of output arguments expected from MatLab.
 * (needs to be 0).
 * @param[out] plhs pointer to the mxArrays containing the results.
 * @param[in] nrhs number of input arguments provided from MatLab.
 * (needs to be 3)
 * @param[in] prhs pointer to the mxArrays containing the input data provided by
 * matlab. prhs[0] needs to contain the handle for the model.
 * prhs[1] needs to contain the function id. prhs[2] needs to contain a matrix where every column represents a subset of variables.
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  //check if data is in correct format
  if(nrhs != 3) {
     mexErrMsgTxt("Wrong number of input variables specified (three needed)\n");
  }
  if(nlhs != 0) {
     mexErrMsgTxt("Wrong number of output variables specified (zero needed)\n");
  }

  // get model out of handle
  typedef opengm::interface::MatlabModelType::GmType GmType;
  GmType& gm = opengm::interface::handle<GmType>::getObject(prhs[0]);

  // get function id
  GmType::FunctionIdentifier::FunctionIndexType functionIndex;
  GmType::FunctionIdentifier::FunctionTypeIndexType functionType;

  if((mxIsUint8(prhs[1]) || mxIsUint16(prhs[1]) || mxIsUint32(prhs[1]) || mxIsUint64(prhs[1])) && (mxGetM(prhs[1]) == 1) && (mxGetN(prhs[1]) == 2)) {
     if(mxIsUint8(prhs[1])) {
        const uint8_T* data = static_cast<const uint8_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     } else if(mxIsUint16(prhs[1])) {
        const uint16_T* data = static_cast<const uint16_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     } else if(mxIsUint32(prhs[1])) {
        const uint32_T* data = static_cast<const uint32_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     } else if(mxIsUint64(prhs[1])) {
        const uint64_T* data = static_cast<const uint64_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     }
  } else {
     mexErrMsgTxt("Unsupported dataformat for function id!");
  }
  GmType::FunctionIdentifier functionID(functionIndex, functionType);

  // get subset of variables and add factor
  if(mxIsNumeric(prhs[2])) {
     if(mxGetNumberOfDimensions(prhs[2]) != 2) {
        mexErrMsgTxt("variables has to be a matrix where every column represents a subset of variables!");
     }
     size_t numFactors = mxGetN(prhs[2]);
     size_t numVariablesPerFactor = mxGetM(prhs[2]);
     typedef opengm::interface::helper::getDataFromMXArray<addFactorsFunctor> factorAdder;
     addFactorsFunctor functor(functionID, gm, numFactors, numVariablesPerFactor);
     factorAdder()(functor, prhs[2]);
  } else {
     mexErrMsgTxt("Unsupported dataformat for subset of variables!");
  }
}
Ejemplo n.º 21
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	const int *dimsf, *dimsg;
	float s[3];

	if (nrhs>4 || nrhs<3 || nlhs>1) mexErrMsgTxt("Incorrect usage.");

	if (!mxIsNumeric(prhs[0]) || !mxIsUint8(prhs[0]) || mxIsComplex(prhs[0]))
		mexErrMsgTxt("Wrong sort of data (1).");
	if (mxGetNumberOfDimensions(prhs[0]) != 3) mexErrMsgTxt("Wrong number of dims (1).");;
	dimsg  = mxGetDimensions(prhs[0]);

	if (!mxIsNumeric(prhs[1]) || !mxIsUint8(prhs[1]) || mxIsComplex(prhs[1]))
		mexErrMsgTxt("Wrong sort of data (2).");
	if (mxGetNumberOfDimensions(prhs[0]) != 3) mexErrMsgTxt("Wrong number of dims (1).");;
	dimsf  = mxGetDimensions(prhs[1]);

	if (!mxIsNumeric(prhs[2]) || !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]))
		mexErrMsgTxt("Wrong sort of matrix.");
	if (mxGetM(prhs[2]) != 4 || mxGetN(prhs[2]) != 4)
		mexErrMsgTxt("Matrix must be 4x4.");

	if (nrhs == 4)
	{
		if (!mxIsNumeric(prhs[3]) || !mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) ||
		     mxGetM(prhs[3])*mxGetN(prhs[3]) != 3)
			mexErrMsgTxt("Invalid skips.");
		s[0] = mxGetPr(prhs[3])[0];
		s[1] = mxGetPr(prhs[3])[1];
		s[2] = mxGetPr(prhs[3])[2];
	}
	else
	{
		s[0] = s[1] = s[2] = 1.0;
	}

	plhs[0] = mxCreateDoubleMatrix(256,256,mxREAL);

	hist2(mxGetPr(prhs[2]), (unsigned char *)mxGetPr(prhs[0]), (unsigned char *)mxGetPr(prhs[1]),
		dimsg, dimsf, mxGetPr(plhs[0]), s);

}
Ejemplo n.º 22
0
void mexFunction(int nlhs, mxArray *plhs[],
	int nrhs, const mxArray *prhs[]){
	/*Declarar las variables locales*/
	mexPrintf("hios\n"); //Tarea1 termina aqui
	double *A, *B, determinante;
	int *pivot, info, Nfilas, Ncolumnas;
	/*Insertar el código */
	if (nrhs != 1){ // nº args diferente de 1
		mexErrMsgTxt("Error. myla, Debe tener un arg de entrada");
	}
	if (!mxIsNumeric(prhs[0])){
		mexErrMsgTxt("Error. El argumento de entrada debe ser una matriz");
	}
	Nfilas = mxGetM(prhs[0]);
	Ncolumnas = mxGetN(prhs[0]);
	if (Nfilas != Ncolumnas){
		mexErrMsgTxt("Error. La matriz debe ser cuadrada");
	}
	if (Nfilas == 0){
		mexErrMsgTxt("Error. La matriz debe no ser vacía");
	}
	if (nlhs > 2){
		mexErrMsgTxt("Error. Debe haber uno o dos args de salida");
	}
	// copia de las variables
	A = mxGetPr(prhs[0]);
	B = (double *)mkl_malloc(Nfilas*Ncolumnas*sizeof(double), 64);
	memcpy(B, A, Nfilas*Ncolumnas*sizeof(double));
	pivot = (int *)mkl_malloc(Nfilas*sizeof(int), 32);
	//procesos computacionales
	info = LAPACKE_dgetrf(LAPACK_COL_MAJOR, Nfilas, Ncolumnas, B, Ncolumnas, pivot);
	determinante = 1.0;
	for (int i = 0; i < Nfilas; i++){
		if (pivot[i] != (i+1)){
			determinante *= -B[i*Ncolumnas + i];
		}
		else{
			determinante *= B[i*Ncolumnas + i];
		}
	}
	// crear los resultados de salida
	plhs[0] = mxCreateDoubleScalar(determinante);
	if (nlhs == 2){
		if (fabs(determinante) < 1.0e-8){
			mexWarnMsgTxt("Matriz singular o casi singular");
		}
		LAPACKE_dgetri(LAPACK_COL_MAJOR, Nfilas, B, Ncolumnas, pivot);
		plhs[1] = mxCreateDoubleMatrix(Nfilas, Ncolumnas, mxREAL);
		double *C = mxGetPr(plhs[1]);
		memcpy(C, B, Nfilas*Ncolumnas*sizeof(double));
	}
	mkl_free(pivot);
	mkl_free(B);
}
Ejemplo n.º 23
0
Archivo: S4mex.c Proyecto: soamaven/S4
static void vec3_check(int arg, const mxArray *prhs[], const char *argname, double *ret){
	int i;
	const double *p;
	if(!mxIsNumeric(prhs[arg]) || 3 != mxGetNumberOfElements(prhs[arg])){
		mexErrMsgIdAndTxt("S4:invalidInput", "Expected 3-vector.");
	}
	p = mxGetPr(prhs[arg]);
	for(i = 0; i < 3; ++i){
		ret[i] = p[i];
	}
}
Ejemplo n.º 24
0
void retrieve_cost( const mxArray* matptr, double& cost){
	// check that I actually received something
	if( matptr == NULL )
		mexErrMsgTxt("missing third or fourth parameter (element index)\n");

	if( 1 != mxGetM(matptr) || !mxIsNumeric(matptr) || 1 != mxGetN(matptr) )
		mexErrMsgTxt("second parameter should be a unique integer array index\n");

	// retrieve cost
	cost = (double) mxGetScalar(matptr);
}
Ejemplo n.º 25
0
 void retrieve_num( const mxArray* matptr, int& num){
	// check that I actually received something
	if( matptr == NULL )
		mexErrMsgTxt("missing third parameter (element index)\n");

	if( 1 != mxGetM(matptr) || !mxIsNumeric(matptr) || 1 != mxGetN(matptr) )
		mexErrMsgTxt("second parameter should be a unique integer array index\n");

	// retrieve index
	num = (int) mxGetScalar(matptr);
}
static double struct_val_default(const mxArray *s, const char *name, double dflt)
{
     mxArray *val = mxGetField(s, 0, name);
     if (val) {
	  CHECK0(mxIsNumeric(val) && !mxIsComplex(val) 
		&& mxGetM(val) * mxGetN(val) == 1,
		"opt fields, other than xtol_abs, must be real scalars");
	  return mxGetScalar(val);
     }
     return dflt;
}
Ejemplo n.º 27
0
MAPTYPE *get_maps(const mxArray *ptr, int *n)
{
    if (mxIsStruct(ptr))
        return(get_maps_struct(ptr, n));
    else if (mxGetNumberOfDimensions(ptr) <= 3 &&
        mxIsNumeric(ptr) && !mxIsComplex(ptr) &&
        !mxIsSparse(ptr))
        return(get_maps_3dvol(ptr, n));
    else
        mexErrMsgTxt("What do I do with this?");
    return((MAPTYPE *)0);
}
Ejemplo n.º 28
0
int32_t CMatlabInterface::get_int()
{
	const mxArray* i=get_arg_increment();
	if (!i || !mxIsNumeric(i) || mxGetN(i)!=1 || mxGetM(i)!=1)
		SG_ERROR("Expected Scalar Integer as argument %d\n", m_rhs_counter);

	double s=mxGetScalar(i);
	if (s-CMath::floor(s)!=0)
		SG_ERROR("Expected Integer as argument %d\n", m_rhs_counter);

	return int32_t(s);
}
Ejemplo n.º 29
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;
}
static double *struct_arrval(const mxArray *s, const char *name, unsigned n,
			     double *dflt)
{
     mxArray *val = mxGetField(s, 0, name);
     if (val) {
	  CHECK0(mxIsNumeric(val) && !mxIsComplex(val) 
		&& mxGetM(val) * mxGetN(val) == n,
		"opt vector field is not of length n");
	  return mxGetPr(val);
     }
     return dflt;
}