extern void sf_internal_set_sim_state_c2_Quadsim(SimStruct* S, const mxArray *st)
{
  ChartInfoStruct *chartInfo = (ChartInfoStruct*) ssGetUserData(S);
  mxArray *plhs[1] = { NULL };

  mxArray *prhs[4];
  int mxError = 0;
  prhs[0] = mxCreateString("chart_simctx_high2raw");
  prhs[1] = mxCreateDoubleScalar(ssGetSFuncBlockHandle(S));
  prhs[2] = mxDuplicateArray(st);      /* high level simctx */
  prhs[3] = (mxArray*) sf_get_sim_state_info_c2_Quadsim();/* state var info */
  mxError = sf_mex_call_matlab(1, plhs, 4, prhs, "sfprivate");
  mxDestroyArray(prhs[0]);
  mxDestroyArray(prhs[1]);
  mxDestroyArray(prhs[2]);
  mxDestroyArray(prhs[3]);
  if (mxError || plhs[0] == NULL) {
    sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_high2raw'.\n");
  }

  set_sim_state_c2_Quadsim((SFc2_QuadsimInstanceStruct*)chartInfo->chartInstance,
    mxDuplicateArray(plhs[0]));
  mxDestroyArray(plhs[0]);
}
示例#2
0
extern void sf_internal_set_sim_state_c5_testYarpReadSHORE(SimStruct* S, const
  mxArray *st)
{
  ChartRunTimeInfo * crtInfo = (ChartRunTimeInfo *)(ssGetUserData(S));
  ChartInfoStruct * chartInfo = (ChartInfoStruct *)(crtInfo->instanceInfo);
  mxArray *plhs[1] = { NULL };

  mxArray *prhs[3];
  int mxError = 0;
  prhs[0] = mxCreateString("chart_simctx_high2raw");
  prhs[1] = mxDuplicateArray(st);      /* high level simctx */
  prhs[2] = (mxArray*) sf_get_sim_state_info_c5_testYarpReadSHORE();/* state var info */
  mxError = sf_mex_call_matlab(1, plhs, 3, prhs, "sfprivate");
  mxDestroyArray(prhs[0]);
  mxDestroyArray(prhs[1]);
  mxDestroyArray(prhs[2]);
  if (mxError || plhs[0] == NULL) {
    sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_high2raw'.\n");
  }

  set_sim_state_c5_testYarpReadSHORE((SFc5_testYarpReadSHOREInstanceStruct*)
    chartInfo->chartInstance, mxDuplicateArray(plhs[0]));
  mxDestroyArray(plhs[0]);
}
示例#3
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
    //Validate input
    if (nrhs != 1) {
        mexErrMsgTxt("Wrong number of input arguments (expected 1)");
    }
    if (nlhs != 1) {
        mexErrMsgTxt("Wrong number of output arguments (expected 1)");
    }
    if (!mxIsClass(prhs[0], MEX_INPUT_CLASS_NAME)) {
        mexErrMsgTxt("Input array of wrong type, you may need to recompile with HIGH_PRECISION on/off");
    }
    if (mxIsComplex(prhs[0])) {
        mexErrMsgTxt("Input array is complex.");
    }

    //Create a copy of indata since it is modified which is not normal matlab behaviour
	mxArray* inArray = mxDuplicateArray(prhs[0]);

    //Get number of dimensions. Note: matlab treats 1d arrays as 2d.
	mwSize ndim = mxGetNumberOfDimensions(inArray);
	const mwSize* dims = mxGetDimensions(inArray);
    if (ndim > 3) {
        mexErrMsgTxt("Input array size not supported.");
    }
    bool is1D = (ndim == 2 && (dims[0] == 1 || dims[1] == 1)); //Classify as 1D if either dimension is 1

	//Validate data size
	mwSize numel = mxGetNumberOfElements(inArray);
	if (numel > INT_MAX) {
		mexErrMsgTxt("Number of elements is to large, has to fit in INT_MAX");
	}

    //Allocate output data
    plhs[0] = mxCreateNumericArray(ndim, dims, MEX_INPUT_CLASS_TYPE, 0);

    //Get the data pointers
	FLOAT* out = mxGetPr(plhs[0]);
	FLOAT* in = mxGetPr(inArray);

    //Perform the wavelet transform
    if (is1D) {
        invwavelet_transform1D(in, (int)(dims[0] * dims[1]), out);
    } else if (ndim == 2) {
        invwavelet_transform2D(in, (int)(dims[0]), (int)(dims[1]), out);
    } else if (ndim == 3) {
        invwavelet_transform3D(in, (int)(dims[0]), (int)(dims[1]), (int)(dims[2]), out);
    }
}
unsigned int
  sf_SMC_AC_Quadcopter_Simulation_ver2_get_eml_resolved_functions_info( int nlhs,
  mxArray * plhs[], int nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

  char commandName[64];
  if (nrhs<2 || !mxIsChar(prhs[0]))
    return 0;

  /* Possible call to get the get_eml_resolved_functions_info */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"get_eml_resolved_functions_info"))
    return 0;

  {
    unsigned int chartFileNumber;
    chartFileNumber = (unsigned int)mxGetScalar(prhs[1]);
    switch (chartFileNumber) {
     case 2:
      {
        extern const mxArray
          *sf_c2_SMC_AC_Quadcopter_Simulation_ver2_get_eml_resolved_functions_info
          (void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c2_SMC_AC_Quadcopter_Simulation_ver2_get_eml_resolved_functions_info
          ();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

     default:
      plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
    }
  }

  return 1;

#else

  return 0;

#endif

}
示例#5
0
void
mexFunction (int nlhs, mxArray* plhs[], int nrhs, 
             const mxArray* prhs[])
{
  mwSize n;
  mwIndex i;

  if (nrhs != 1 || ! mxIsCell (prhs[0]))
    mexErrMsgTxt ("expects cell");

  n = mxGetNumberOfElements (prhs[0]);
  n = (n > nlhs ? nlhs : n);
  
  for (i = 0; i < n; i++)
    plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
}
示例#6
0
void mexFunction( int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray*prhs[] )
     
{
	double *W = mxGetPr(prhs[0]);
	double *p = mxGetPr(prhs[1]);
	int wm = mxGetM(prhs[0]);
	int wn = mxGetN(prhs[0]);
	int k = mxGetScalar(prhs[2]);
	plhs[0] = mxDuplicateArray(prhs[3]);/* lemasolom a tombot, mert az input parameter const */
	double *x = mxGetPr(plhs[0]);
	bool *freePixels = mxGetLogicals(prhs[4]);
	double *beta = mxGetPr(prhs[5]);
	double *gamma = mxGetPr(prhs[6]);
	int numIters = mxGetScalar(prhs[7]);
	SART(W,wm,wn,p,k,x,freePixels,beta,gamma, numIters);
}
示例#7
0
/**
 * @brief Interfaces C and Matlab data.
 * This function is the MEX-file gateway routine. Please see the Matlab
 * MEX-file documentation (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f43721.html)
 * for more information.
 */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{

  /* allocate variables */
  struct histcond *in;
  struct options_entropy *opts;
  int status;

  /* check number of inputs (nargin) and outputs (nargout) */
  if((nrhs<1) | (nrhs>2))
    mexErrMsgIdAndTxt("STAToolkit:infocond:numArgs","1 or 2 input arguments required.");
  if((nlhs<1) | (nlhs>2))
    mexErrMsgIdAndTxt("STAToolkit:infocond:numArgs","1 or 2 outputs argument required.");

  /* get or set options */
  if(nrhs<2)
    opts = ReadOptionsEntropy(mxCreateEmptyStruct());
  else if(mxIsEmpty(prhs[1]))
    opts = ReadOptionsEntropy(mxCreateEmptyStruct());
  else
    opts = ReadOptionsEntropy(prhs[1]);

  plhs[0] = mxDuplicateArray(prhs[0]);

  in = ReadHistCond(plhs[0],opts);

  status = InfoCondComp(in,opts);
  if(status!=EXIT_SUCCESS)
    mexWarnMsgIdAndTxt("STAToolkit:infocond:failure","Function infocond returned with errors. Please check messages.");

  /* Augment the mx histogram with the new info */
  WriteHistCondAgain(in,plhs[0]);

  /* output options used */
  if(nrhs<2)
    plhs[1] = WriteOptionsEntropy(mxCreateEmptyStruct(),opts);
  else if(mxIsEmpty(prhs[1]))
    plhs[1] = WriteOptionsEntropy(mxCreateEmptyStruct(),opts);
  else
    plhs[1] = WriteOptionsEntropy(prhs[1],opts);

  mxFree(in);

  return;
}
示例#8
0
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
  // Declare variables
  int nz, j;
  double *x1, *x2, *y1, *y2;
  mxArray *mat, *p;
  double *pr, *pd;
  
  // Get the number of elements in the input argument
  nz = mxGetNumberOfElements(prhs[0]);
  
  // Get input pointer
  x1 = (double *)mxGetData(prhs[0]);
  x2 = (double *)mxGetData(prhs[1]);
  y1 = (double *)mxGetData(prhs[2]);
  y2 = (double *)mxGetData(prhs[3]);
  
  // Get output pointer
  plhs[0] = mxCreateCellMatrix(1, (mwSize)nz);
  
  // Initialize output
  mat = mxCreateDoubleMatrix(5, 2, mxREAL);
  pr = (double *)mxGetData(mat);
   
  for (j=0; j<nz; j++)
  {

     pr[0] = (double)x1[j];
     pr[3] = (double)x1[j];
     pr[4] = (double)x1[j];
     
     pr[1] = (double)x2[j];
     pr[2] = (double)x2[j];
     
     pr[5] = (double)y1[j];
     pr[6] = (double)y1[j];
     pr[9] = (double)y1[j];

     pr[7] = (double)y2[j];
     pr[8] = (double)y2[j];
     
     mxSetCell(plhs[0], j, mxDuplicateArray(mat));
  }
  return;
}
示例#9
0
文件: submit.c 项目: nsteinme/signals
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	if (nrhs == 3) {
		int netid = (int)mxGetScalar(prhs[0]);
		size_t nodeid = (size_t)roundl(mxGetScalar(prhs[1]));
		size_t i;
		mxArray *updatedNodes = (mxArray *)NULL;
		for (i = 0; i < 1; i++) {
			mxArray *val = mxDuplicateArray(prhs[2]);
			mexMakeArrayPersistent(val);
			updatedNodes = sqTransact(netid, nodeid, val);
		}
		if (updatedNodes)
			plhs[0] = updatedNodes;
	}
	else {
		mexErrMsgIdAndTxt("sq:notEnoughArgs", "Not enough input arguments");
	}
}
示例#10
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    const mxArray *model, *data;
    mxArray *zeta, *windex, *wcount;
    double  *zetai, *windexi, *wcounti, *Esticks, *Eloglambda, *Eloggamma;
    double  *smallphi, *sstopicwordptr, *ssfeatures, *count2, *option;
    int N, ndistWords, K1, K2, V;
    
    model = prhs[0];
    data  = prhs[1];
    N     = (int)mxGetScalar(mxGetField(model,0,"N"));
    K1    = (int)mxGetScalar(mxGetField(model,0,"K1"));
    K2    = (int)mxGetScalar(mxGetField(model,0,"K2"));
    V     = (int)mxGetScalar(mxGetField(model,0,"V"));
    
    zeta         = mxGetField(model,0,"zeta");
    windex       = mxGetField(data,0,"windex");
    wcount       = mxGetField(data,0,"wcount");
    smallphi     = (double*)mxGetPr(mxGetField(model,0,"smallphi"));
    Esticks      = (double*)mxGetPr(prhs[2]); // E_{log(\pi)}
    Eloglambda   = (double*)mxGetPr(prhs[3]); // psi(\lambda)
    Eloggamma    = (double*)mxGetPr(prhs[4]); // sum of psi(\lambda) over vocabulary
    count2       = (double*)mxGetPr(prhs[5]); // counter for controlling initialization
    option       = (double*)mxGetPr(prhs[6]); // option=1, NPDSLDA; (int)option[0]==0, NPLDA
    
    plhs[0] = mxCreateCellMatrix(1,N);
    if((int)option[0]==1)
    {
        plhs[1] = mxCreateDoubleMatrix((K1+K2),V,mxREAL);
        plhs[2] = mxCreateDoubleMatrix(N,(K1+K2),mxREAL);
    }
    else
    {
        plhs[1] = mxCreateDoubleMatrix(K1,V,mxREAL);
        plhs[2] = mxCreateDoubleMatrix(N,K1,mxREAL);
    }
    sstopicwordptr = mxGetPr(plhs[1]);
    ssfeatures = mxGetPr(plhs[2]);
    
    for (int i = 0; i < N; i++)
    {
        zetai   = (double*)mxGetPr(mxDuplicateArray (mxGetCell (zeta, i)));     // pointer to zeta{i}
        windexi = (double*)mxGetPr(mxDuplicateArray (mxGetCell (windex, i)));   // pointer to windex{i}
        wcounti = (double*)mxGetPr(mxDuplicateArray (mxGetCell (wcount, i)));   // pointer to wcount{i}
        ndistWords = mxGetM(mxDuplicateArray (mxGetCell (windex, i)));
        if(mxGetN(mxDuplicateArray (mxGetCell (windex, i)))>ndistWords)
            ndistWords = mxGetN(mxDuplicateArray (mxGetCell (windex, i)));
        //mexPrintf("hey here! %d %d\n", i, ndistWords);
        update_zeta_i(plhs[0], sstopicwordptr, ssfeatures, zetai, windexi, wcounti, model, data, Esticks, Eloglambda, Eloggamma, smallphi, ndistWords, i, count2, option);
    }
    return;
}
示例#11
0
void 
mexFunction( int nlhs, mxArray *plhs[],  int nrhs, const mxArray *prhs[])
{
    mwSize i, n;
    double *pr, *pi;
    double inf, nan;
    
    /* Check for proper number of input and output arguments */    
    if (nrhs != 1) {
	mexErrMsgTxt("One input argument required.");
    } 
    if(nlhs > 1){
	mexErrMsgTxt("Too many output arguments.");
    }
    
    /* Check data type of input argument  */
    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {
	mexErrMsgTxt("Input argument must be of type real double.");
    }	
    
    /* Duplicate input array */
    plhs[0]=mxDuplicateArray(prhs[0]);
    
    pr = mxGetPr(plhs[0]);
    pi = mxGetPi(plhs[0]);
    n = mxGetNumberOfElements(plhs[0]);
    inf = mxGetInf();
    nan=mxGetNaN();

    /* Check for 0, in real part of data, if the data is zero, replace
       with NaN.  Also check for INT_MAX and INT_MIN and replace with
       INF/-INF respectively.  */
    for(i=0; i < n; i++) {
	if (pr[i] == 0){
	    pr[i]=nan;
	}
	else if ( pr[i]>= INT_MAX){
	    pr[i]=inf;
	}
	else if (pr[i]<= INT_MIN){
	    pr[i]=-(inf);
	}
    }
}
示例#12
0
void ttSetDataAux(const char *nameOfTask, const mxArray *data) {
    DataNode* dn = getNode(nameOfTask, rtsys->taskList);
    if (dn == NULL) {
        char buf[200];
        sprintf(buf, "ttSetData: Non-existent task '%s'!", nameOfTask);
        TT_MEX_ERROR(buf);
        return;
    }
    UserTask* task = (UserTask*) dn->data;
    if (task->dataMATLAB == NULL) {
        char buf[200];
        sprintf(buf, "ttSetData: Task '%s' doesn't have data!", nameOfTask);
        TT_MEX_ERROR(buf);
        return;
    }
    mxDestroyArray(task->dataMATLAB);
    task->dataMATLAB = mxDuplicateArray(data);
    mexMakeArrayPersistent(task->dataMATLAB);
}
示例#13
0
void mexFunction( int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray*prhs[] )
     
{ 
    
    int i,x,y,sliceInd,dataSliceInd,ind,nBounds,nBoundsSlice,nDataSlice;
    double *sz, *dataSz, *bounds, *res, *data;
    int start1,start2,end1,end2;
    
    plhs[0] = mxDuplicateArray(prhs[6]);
    res = mxGetPr(plhs[0]);
    
    data =mxGetPr(prhs[0]);
    bounds = mxGetPr(prhs[1]);
    nBounds = (int) mxGetPr(prhs[2])[0];
    nBoundsSlice = (int) mxGetPr(prhs[3])[0];
    dataSz = mxGetPr(prhs[4]);
    nDataSlice = (int) mxGetPr(prhs[5])[0];
    
    for (i=0; i < nBounds; i++) {
    /*for (i=0; i < 1; i++) {*/
        sliceInd = i*nBoundsSlice;
        
        /* change to 0-indexed. Skip over angles during indexing.*/
        start1 = (int) bounds[sliceInd]-1;
        end1 = (int) bounds[sliceInd+3]-1;
        start2 = (int) bounds[sliceInd+1]-1;
        end2 = (int) bounds[sliceInd+4]-1;
        /*end2 = (int) bounds[sliceInd+3]-1;*/
        
        dataSliceInd = i*nDataSlice;
        ind = 0;
        
        /* careful with ensuring raster order!!!!*/
        for (y = start2; y <= end2; y++) {
            for (x = start1; x <= end1; x++) {            
                res[dataSliceInd+ind] = data[x+y*((int) dataSz[0])];
                ind++;
            }
        }
        
    }
}
示例#14
0
文件: gammaln.c 项目: 2php/lrslibrary
void mexFunction(int nlhs, mxArray *plhs[],
		 int nrhs, const mxArray *prhs[])
{
  mwSize ndims, len, i, nnz;
  mwSize *dims;
  double *indata, *outdata, d;

  if((nlhs > 1) || (nrhs < 1) || (nrhs > 2))    
    mexErrMsgTxt("Usage: x = gammaln(n) or gammaln(n,d)");

  /* prhs[0] is first argument.
   * mxGetPr returns double*  (data, col-major)
   */
  ndims = mxGetNumberOfDimensions(prhs[0]);
  dims = (mwSize*)mxGetDimensions(prhs[0]);
  indata = mxGetPr(prhs[0]);
  len = mxGetNumberOfElements(prhs[0]);

  if(mxIsSparse(prhs[0])) {
    plhs[0] = mxDuplicateArray(prhs[0]);
    /* number of nonzero entries */
    nnz = mxGetJc(prhs[0])[mxGetN(prhs[0])];
    if(nnz != mxGetNumberOfElements(prhs[0])) {
      mexErrMsgTxt("Cannot handle sparse n.");
    }
  } else {
    /* plhs[0] is first output */
    plhs[0] = mxCreateNumericArray(ndims, dims, mxDOUBLE_CLASS, mxREAL);
  }
  outdata = mxGetPr(plhs[0]);

  /* compute gammaln of every element */
  if(nrhs == 1) {
    for(i=0;i<len;i++)
      *outdata++ = gammaln(*indata++);
  } else {
    if(mxGetNumberOfElements(prhs[1]) != 1) mexErrMsgTxt("d is not scalar.");
    d = *mxGetPr(prhs[1]);
    for(i=0;i<len;i++)
      *outdata++ = gammaln2(*indata++,d);
  }
}
void mexFunction(	int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{	int m,n;
	double *r_in;
	double *A, *B ;  
	int max_order;
	mxArray *tmpmxptr;


/* ALLOCATE memory for the output array of the same size as the input */
	m = mxGetM(prhs[1]);
	n = mxGetN(prhs[1]);
	if(m!=6) 
		mexErrMsgTxt("Second argument must be a 6 x N matrix");
	

	tmpmxptr =mxGetField(prhs[0],0,"PolynomA");
	if(tmpmxptr)
	    A = mxGetPr(tmpmxptr);
	else
		mexErrMsgTxt("Required field 'PolynomA' was not found in the element data structure"); 
				    
	tmpmxptr =mxGetField(prhs[0],0,"PolynomB");
	if(tmpmxptr)   
	    B = mxGetPr(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'PolynomB' was not found in the element data structure");
					    
	tmpmxptr = mxGetField(prhs[0],0,"MaxOrder");
	if(tmpmxptr)
	    max_order = (int)mxGetScalar(tmpmxptr);
	else
		mexErrMsgTxt("Required field 'MaxOrder' was not found in the element data structure");
		
    plhs[0] = mxDuplicateArray(prhs[1]);
	r_in = mxGetPr(plhs[0]);

	ThinMPolePass(r_in,A,B,max_order, n);
	

}
示例#16
0
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
    
    /* VARIABLES DECLARATION */
    double sigma2;
    double T;
	double BaseAmp;
    int *SegLen;
    double *SegAmp;
    int L;
    double *OutSegAmp;
    
    // Checking number of input/output parameters
    if (nrhs != 5){ 
    	mexErrMsgTxt("5 input arguments are required"); 
    }
    
    if (nlhs != 1) {
    	mexErrMsgTxt("1 output arguments are required"); 
    }

       
    /* Getting Input parameters */
    SegLen=(int*)mxGetPr(prhs[0]);    
    SegAmp=mxGetPr(prhs[1]); //NotNecessary 
	BaseAmp=mxGetScalar(prhs[2]);  
    sigma2=mxGetScalar(prhs[3]);    
    T=mxGetScalar(prhs[4]);

    L = mxGetNumberOfElements(prhs[0]);    

    // Preparing output results
	plhs[0]=mxDuplicateArray(prhs[1]);
    OutSegAmp= mxGetPr(plhs[0]);

	CollapseAmpTtest(OutSegAmp,SegLen,L,BaseAmp,sigma2,T);
			

}
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
   
  if (nrhs!=2)	mexErrMsgTxt("Two inputs required");

  //check class
  mxClassID classID = mxGetClassID(dataIn);
  
  //get dimensions  
  mwSize ndims = mxGetM(dataIn);
  mwSize npoints = mxGetN(dataIn);
  
  //get metric
  char tt[100];
  NormalizeMetric metric;
  mxGetString(metricIn, tt, 90);
  string metricStr(tt);
  if (metricStr=="l1")            metric = NORMALIZE_METRIC_L1;
  else if (metricStr=="l2")       metric = NORMALIZE_METRIC_L2;
  else                            metric = NORMALIZE_METRIC_NONE; 
//    mexErrMsgTxt("Unknown distance function.");

  //allocate output
  dataOut = mxDuplicateArray(dataIn);  //(mxArray*)dataIn; //
  
  //call agg cluster  
#define __CASE(CLASS)                                                   \
  {                                                                     \
    /*get data*/                                                        \
    Data<TYPEOF_##CLASS> data;                                          \
    fillData(data, dataOut);                                            \
    /*normalize*/                                                       \
    normalize(data, metric);                                            \
  }
            
    __SWITCH(classID, __CASE)    
    
}
示例#18
0
mxArray *WriteOptionsDirect(const mxArray *in,struct options_direct *opts)
{
  mxArray *out;

  out = mxDuplicateArray(in);

  WriteOptionsDoubleMember(out,"start_time",opts->t_start,opts->t_start_flag);
  WriteOptionsDoubleMember(out,"end_time",opts->t_end,opts->t_end_flag);
  WriteOptionsDoubleMember(out,"counting_bin_size",opts->Delta,opts->Delta_flag);
  WriteOptionsIntMember(out,"sum_spike_trains",opts->sum_spike_trains,opts->sum_spike_trains_flag);
  WriteOptionsIntMember(out,"permute_spike_trains",opts->permute_spike_trains,opts->permute_spike_trains_flag);
  WriteOptionsIntMember(out,"words_per_train",opts->words_per_train,opts->words_per_train_flag);
  WriteOptionsIntMember(out,"legacy_binning",opts->legacy_binning,opts->legacy_binning_flag);
  if((opts->letter_cap_flag) && (opts->letter_cap==0))
    WriteOptionsDoubleMember(out,"letter_cap",mxGetInf(),opts->letter_cap_flag);
  else
    WriteOptionsIntMember(out,"letter_cap",opts->letter_cap,opts->letter_cap_flag);

  mxFree(opts);

  return out;
}
示例#19
0
// read the input features into internal data structures
int read_problem_dense(const mxArray *label_vec, const mxArray *instance_mat){
  int i, label_vector_row_num;
  double *samples;
  mxArray *instance_mat_col; // instance sparse matrix in column format
  
  if(col_format_flag)
    instance_mat_col = (mxArray *)instance_mat;
  else{
    // transpose instance matrix
    mxArray *prhs[1], *plhs[1];
    prhs[0] = mxDuplicateArray(instance_mat);
    if(mexCallMATLAB(1, plhs, 1, prhs, "transpose")){
      mexPrintf("Error: cannot transpose training instance matrix\n");
      return -1;
    }
    instance_mat_col = plhs[0];
    mxDestroyArray(prhs[0]);
  }

  // compute the dimensions of the features
  nvec = (int) mxGetN(instance_mat_col);
  dim  = (int) mxGetM(instance_mat_col);
  
  label_vector_row_num = (int) mxGetM(label_vec);
  if(label_vector_row_num!= nvec){
    mexPrintf("Length of label vector does not match # of instances.\n");
    return -1;
  }
	
  // obtain pointers to the data/labels
  y = mxGetPr(label_vec);
  samples = mxGetPr(instance_mat_col);
  x = new double*[nvec];
  
  for(i=0;i<nvec;i++)
    x[i] = &samples[i*dim];
  
  return 0;
}
示例#20
0
void mexFunction(
   int nlhs, mxArray *plhs[],
   int nrhs, const mxArray *prhs[])
{
  mwSize n; /*mxGetNumberOfElements*/
  double *p, *pend, *x; /*mxGetPr, p, mxGetPr*/

  /* Error checking on inputs */  
  if (nrhs<1) mexErrMsgTxt("Not enough input arguments.");
  if (nrhs>1) mexErrMsgTxt("Too many input arguments.");
  if (nlhs>1) mexErrMsgTxt("Too many output arguments.");
  if (!mxIsDouble(prhs[0]) && !mxIsSparse(prhs[0]))
      mexErrMsgTxt("Function not defined for variables of input class");
  if (mxIsComplex(prhs[0]))
      mexErrMsgTxt("X must be real.");

  x=mxGetPr(prhs[0]);
  n=mxGetNumberOfElements(prhs[0]);
  plhs[0]=mxDuplicateArray(prhs[0]);
  p=mxGetPr(plhs[0]);
  for (pend=p+n; p<pend; p++,x++) { *p=psi(*x);} 

}
示例#21
0
mxArray* MakeStructCopyAndCreatePointer(const mxArray *data)
{
  const char *field_names[] = {"data"};
  mxArray *A, *address, *copy_data;

  A = CreateObject(1, 1, 1, field_names, "pointer");
  address = mxCreateStructMatrix(1, 1, 1, field_names);
  mexMakeArrayPersistent(address);
  SetPointerData(A, address);

  if (data)
  {
    copy_data = mxDuplicateArray(data);
    mexMakeArrayPersistent(copy_data);
  }            
  else
    copy_data = NULL;


  SetPointerData(address, copy_data);

  return A;
}
示例#22
0
void mexFunction(
   int nlhs, mxArray *plhs[],
   int nrhs, const mxArray *prhs[])
{
  int n;
  double *x, *xend;

  /* Error checking on inputs */  
  if (nrhs<1) mexErrMsgTxt("Not enough input arguments.");
  if (nrhs>1) mexErrMsgTxt("Too many input arguments.");
  /*if (nlhs<1) mexErrMsgTxt("Not enough output arguments.");*/
  if (nlhs>1) mexErrMsgTxt("Too many output arguments.");
  if (!mxIsDouble(prhs[0]) && !mxIsSparse(prhs[0]))
      mexErrMsgTxt("Function not defined for variables of input class");
  if (mxIsComplex(prhs[0]))
      mexErrMsgTxt("X must be real.");

  n=mxGetNumberOfElements(prhs[0]);
  plhs[0]=mxDuplicateArray(prhs[0]);
  x=mxGetPr(plhs[0]);
  xend=x+n;
  for (;x<xend;x++) *x = icdfn(*x);
}
示例#23
0
void mexFunction(int nlhs, mxArray *plhs[],
		 int nrhs, const mxArray *prhs[])
{
  int ndims, len, i, nnz;
  int *dims;
  double *indata, *outdata;

  if((nrhs != 1) || (nlhs > 1))    
    mexErrMsgTxt("Usage: x = trigamma(n)");

  /* prhs[0] is first argument.
   * mxGetPr returns double*  (data, col-major)
   * mxGetM returns int  (rows)
   * mxGetN returns int  (cols)
   */
  ndims = mxGetNumberOfDimensions(prhs[0]);
  dims = (int*)mxGetDimensions(prhs[0]);
  indata = mxGetPr(prhs[0]);
  len = mxGetNumberOfElements(prhs[0]);

  if(mxIsSparse(prhs[0])) {
    plhs[0] = mxDuplicateArray(prhs[0]);
    /* number of nonzero entries */
    nnz = mxGetJc(prhs[0])[mxGetN(prhs[0])];
    if(nnz != mxGetNumberOfElements(prhs[0])) {
      mexErrMsgTxt("Cannot handle sparse n.");
    }
  } else {
    /* plhs[0] is first output */
    plhs[0] = mxCreateNumericArray(ndims, dims, mxDOUBLE_CLASS, mxREAL);
  }
  outdata = mxGetPr(plhs[0]);

  /* compute trigamma of every element */
  for(i=0;i<len;i++)
    *outdata++ = trigamma(*indata++);
}
static void KIM_init()
{
    mxArray *empty;

    /* Allocate space for global KINSOL and MATLAB data structures */

    kim_Kdata = (kim_KINSOLdata) mxMalloc(sizeof(struct kim_KINSOLdataStruct));
    kim_Mdata = (kim_MATLABdata) mxMalloc(sizeof(struct kim_MATLABdataStruct));

    /* Initialize global KINSOL data */

    kin_mem  = NULL;
    bbd_data = NULL;

    y = NULL;

    N = 0;

    ls  = LS_DENSE;
    pm  = PM_NONE;

    /* Initialize global MATLAB data */

    empty = mxCreateDoubleMatrix(0,0,mxREAL);

    mx_data     = mxDuplicateArray(empty);

    mx_SYSfct   = mxDuplicateArray(empty);
    mx_JACfct   = mxDuplicateArray(empty);
    mx_PSETfct  = mxDuplicateArray(empty);
    mx_PSOLfct  = mxDuplicateArray(empty);
    mx_GLOCfct  = mxDuplicateArray(empty);
    mx_GCOMfct  = mxDuplicateArray(empty);

    mxDestroyArray(empty);

    return;
}
示例#25
0
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum {IN_I = 0, IN_S, IN_END} ;
  enum {OUT_J = 0} ;
  int opt ;
  int next = IN_END ;
  mxArray const  *optarg ;

  int padding = VL_PAD_BY_CONTINUITY ;
  int kernel = GAUSSIAN ;
  int flags ;
  vl_size step = 1 ;
  int verb = 0 ;
  double sigma ;
  mxClassID classid ;

  mwSize M, N, K, M_, N_, ndims ;
  mwSize dims_ [3] ;
  mwSize const * dims ;

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

  if (nin < 2) {
    mexErrMsgTxt("At least two input arguments required.");
  } else if (nout > 1) {
    mexErrMsgTxt("Too many output arguments.");
  }

  while ((opt = vlmxNextOption (in, nin, options, &next, &optarg)) >= 0) {
    switch (opt) {
      case opt_padding :
      {
        enum {buflen = 32} ;
        char buf [buflen] ;
        if (!vlmxIsString(optarg, -1)) {
          vlmxError(vlmxErrInvalidArgument,
                   "PADDING argument must be a string.") ;
        }
        mxGetString(optarg, buf, buflen) ;
        buf [buflen - 1] = 0 ;
        if (vlmxCompareStringsI("zero", buf) == 0) {
          padding = VL_PAD_BY_ZERO ;
        } else if (vlmxCompareStringsI("continuity", buf) == 0) {
          padding = VL_PAD_BY_CONTINUITY ;
        } else {
          vlmxError(vlmxErrInvalidArgument,
                   "PADDING must be either ZERO or CONTINUITY, was '%s'.",
                   buf) ;
        }
        break ;
      }

      case opt_subsample :
        if (!vlmxIsPlainScalar(optarg)) {
          vlmxError(vlmxErrInvalidArgument,
                   "SUBSAMPLE must be a scalar.") ;
        }
        step = *mxGetPr(optarg) ;
        if (step < 1) {
          vlmxError(vlmxErrInvalidArgument,
                   "SUBSAMPLE must be not less than one.") ;
        }
        break ;

      case opt_kernel :
      {
        enum {buflen = 32} ;
        char buf [buflen] ;
        if (!vlmxIsString(optarg, -1)) {
          vlmxError(vlmxErrInvalidArgument,
                   "KERNEL argument must be a string.") ;
        }
        mxGetString(optarg, buf, buflen) ;
        buf [buflen - 1] = 0 ;
        if (vlmxCompareStringsI("gaussian", buf) == 0) {
          kernel = GAUSSIAN ;
        } else if (vlmxCompareStringsI("triangular", buf) == 0) {
          kernel = TRIANGULAR ;
        } else {
          vlmxError(vlmxErrInvalidArgument,
                   "Unknown kernel type '%s'.",
                   buf) ;
        }
        break ;
      }

      case opt_verbose :
        ++ verb ;
        break ;

      default:
        abort() ;
    }
  }

  if (! vlmxIsPlainScalar(IN(S))) {
    vlmxError(vlmxErrInvalidArgument,
             "S must be a real scalar.") ;
  }

  classid = mxGetClassID(IN(I)) ;

  if (classid != mxDOUBLE_CLASS &&
      classid != mxSINGLE_CLASS) {
    vlmxError(vlmxErrInvalidArgument,
             "I must be either DOUBLE or SINGLE.") ;
  }
  if (mxGetNumberOfDimensions(IN(I)) > 3) {
    vlmxError(vlmxErrInvalidArgument,
             "I must be either a two or three dimensional array.") ;
  }

  ndims = mxGetNumberOfDimensions(IN(I)) ;
  dims = mxGetDimensions(IN(I)) ;
  M = dims[0] ;
  N = dims[1] ;
  K = (ndims > 2) ? dims[2] : 1 ;

  sigma = * mxGetPr(IN(S)) ;
  if ((sigma < 0.01) && (step == 1)) {
    OUT(J) = mxDuplicateArray(IN(I)) ;
    return ;
  }

  M_ = (M - 1) / step + 1 ;
  N_ = (N - 1) / step + 1 ;
  dims_ [0] = M_ ;
  dims_ [1] = N_ ;
  if (ndims > 2) dims_ [2] = K ;

  OUT(J) = mxCreateNumericArray(ndims, dims_, classid, mxREAL) ;

  if (verb) {
    char const *classid_str = 0, *kernel_str = 0, *padding_str = 0 ;
    switch (padding) {
      case VL_PAD_BY_ZERO       : padding_str = "with zeroes" ; break ;
      case VL_PAD_BY_CONTINUITY : padding_str = "by continuity" ; break ;
      default: abort() ;
    }
    switch (classid) {
      case mxDOUBLE_CLASS: classid_str = "DOUBLE" ; break ;
      case mxSINGLE_CLASS: classid_str = "SINGLE" ; break ;
      default: abort() ;
    }
    switch (kernel) {
      case GAUSSIAN:   kernel_str = "Gaussian" ; break ;
      case TRIANGULAR: kernel_str = "triangular" ; break ;
      default: abort() ;
    }

    mexPrintf("vl_imsmooth: [%dx%dx%d] -> [%dx%dx%d] (%s, subsampling step %d)\n",
              N, M, K, N_, M_, K, classid_str, step) ;
    mexPrintf("vl_imsmooth: padding: %s\n", padding_str) ;
    mexPrintf("vl_imsmooth: kernel: %s\n", kernel_str) ;
    mexPrintf("vl_imsmooth: sigma: %g\n", sigma) ;
    mexPrintf("vl_imsmooth: SIMD enabled: %s\n",
              vl_get_simd_enabled() ? "yes" : "no") ;
  }

  /* -----------------------------------------------------------------
   *                                                        Do the job
   * -------------------------------------------------------------- */
  flags  = padding ;
  flags |= VL_TRANSPOSE ;

  switch (classid) {
    case mxSINGLE_CLASS:
      _vl_imsmooth_smooth_f ((float*) mxGetPr(OUT(J)),
                             M_, N_,
                             (float const*) mxGetPr(IN(I)),
                             M, N, K,
                             kernel, sigma, step, flags) ;
      break ;

    case mxDOUBLE_CLASS:
      _vl_imsmooth_smooth_d ((double*) mxGetPr(OUT(J)),
                             M_, N_,
                             (double const*) mxGetPr(IN(I)),
                             M, N, K,
                             kernel, sigma, step, flags) ;
      break ;

    default:
      abort() ;
  }
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	
	//declare variables
    mxArray *centers_in_m, *beaddata, *numlinedata, *radius_in_m, *img_in_m, *maxima_out_m, *avg_out_m;
    const mwSize *dimsimg;
    double *centers, *maxima, *img, *avg;
	double radval;
	int beadnum, xmin, xmax, ymin, ymax, beaditr, dimximg, dimyimg, dimy, numline;
    int y,x,max, sum, counter;
	
	//associate inputs
    centers_in_m = mxDuplicateArray(prhs[0]);
	beaddata = mxDuplicateArray(prhs[1]);
	numlinedata = mxDuplicateArray(prhs[2]);
	radius_in_m = mxDuplicateArray(prhs[3]);
	img_in_m = mxDuplicateArray(prhs[4]);
	
	
	//figure out dimensions
    dimsimg = mxGetDimensions(prhs[4]);
    dimyimg = (int)dimsimg[0]; dimximg = (int)dimsimg[1];
	
	
	//associate input pointers
	
	centers = mxGetPr(centers_in_m);
	//bead = mxGetPr(bead_in_m);
	//radius = mxGetPr(radius_in_m);
	img = mxGetPr(img_in_m);
	//associate outputs
	radval = mxGetScalar(radius_in_m);
	beadnum = (int)(mxGetScalar(beaddata));
	numline = (int)(mxGetScalar(numlinedata));
	//radval = radius[0];
	//dimy = 2*.7*radval+1;
    maxima_out_m = plhs[0] = mxCreateDoubleMatrix(numline,beadnum, mxREAL);
	avg_out_m = plhs[1] = mxCreateDoubleMatrix(beadnum,1,mxREAL);
	//associate output pointers
	maxima = mxGetPr(maxima_out_m);
	avg = mxGetPr(avg_out_m);
	
	
	
	
	//do something
	for(beaditr = 0; beaditr < beadnum; beaditr++){
		
		counter = 0;
		
		xmin = (int)(centers[beaditr] - radval*1.5);
		xmax = (int)(centers[beaditr] + radval*1.5);
		ymin = centers[beaditr+beadnum] - 0.5*numline;
		ymax = centers[beaditr+beadnum] + 0.5*numline;
		  sum = 0;
		//mexPrintf("ymin%d ymax:%d xmin:%d xmax:%d dimyimg:%d max:%d\n",ymin,ymax, xmin, xmax,dimyimg, (xmax-1)*dimyimg+y-1);
		for(y=ymin;y<=ymax;y++)
		{
			
			counter ++;
			max = 0;
		  
			for(x=xmin;x<=xmax;x++)
			{
				if(img[(x-1)*dimyimg+y-1]>max){ //adds 5 to every element in a
					max = img[(x-1)*dimyimg+y-1];
				}
			}
			maxima[counter-1 + beaditr*numline]=max;
			sum+= max;
			//mexPrintf("%d\n", max);
			//mexPrintf("beaditr now: %d\n", counter-1 + beaditr*dimy);
			
		}
		avg[beaditr] = (double)(sum)/(double)(counter);
	}
	
	//mexPrintf("%d\n",dimximg);
	
    return;
}
示例#27
0
// Interface function of matlab
// now assume prhs[0]: label prhs[1]: features
void mexFunction( int nlhs, mxArray *plhs[],
		int nrhs, const mxArray *prhs[] )
{
	const char *error_msg;

	// fix random seed to have same results for each run
	// (for cross validation and probability estimation)
	srand(1);

	if(nlhs > 1)
	{
		exit_with_help();
		fake_answer(nlhs, plhs);
		return;
	}

	// Transform the input Matrix to libsvm format
	if(nrhs > 1 && nrhs < 4)
	{
		int err;

		if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) {
			mexPrintf("Error: label vector and instance matrix must be double\n");
			fake_answer(nlhs, plhs);
			return;
		}

		if(parse_command_line(nrhs, prhs, NULL))
		{
			exit_with_help();
			svm_destroy_param(&param);
			fake_answer(nlhs, plhs);
			return;
		}

		if(mxIsSparse(prhs[1]))
		{
			if(param.kernel_type == PRECOMPUTED)
			{
				// precomputed kernel requires dense matrix, so we make one
				mxArray *rhs[1], *lhs[1];

				rhs[0] = mxDuplicateArray(prhs[1]);
				if(mexCallMATLAB(1, lhs, 1, rhs, "full"))
				{
					mexPrintf("Error: cannot generate a full training instance matrix\n");
					svm_destroy_param(&param);
					fake_answer(nlhs, plhs);
					return;
				}
				err = read_problem_dense(prhs[0], lhs[0]);
				mxDestroyArray(lhs[0]);
				mxDestroyArray(rhs[0]);
			}
			else
				err = read_problem_sparse(prhs[0], prhs[1]);
		}
		else
			err = read_problem_dense(prhs[0], prhs[1]);

		// svmtrain's original code
		error_msg = svm_check_parameter(&prob, &param);

		if(err || error_msg)
		{
			if (error_msg != NULL)
				mexPrintf("Error: %s\n", error_msg);
			svm_destroy_param(&param);
			free(prob.y);
			free(prob.x);
			free(x_space);
			fake_answer(nlhs, plhs);
			return;
		}

		if(cross_validation)
		{
			double *ptr;
			plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
			ptr = mxGetPr(plhs[0]);
			ptr[0] = do_cross_validation();
		}
		else
		{
			int nr_feat = (int)mxGetN(prhs[1]);
			const char *error_msg;
			model = svm_train(&prob, &param);
			error_msg = model_to_matlab_structure(plhs, nr_feat, model);
			if(error_msg)
				mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg);
			svm_free_and_destroy_model(&model);
		}
		svm_destroy_param(&param);
		free(prob.y);
		free(prob.x);
		free(x_space);
	}
	else
	{
		exit_with_help();
		fake_answer(nlhs, plhs);
		return;
	}
}
示例#28
0
int read_problem_sparse(const mxArray *label_vec, const mxArray *instance_mat)
{
	int i, j, k, low, high;
	mwIndex *ir, *jc;
	int elements, max_index, num_samples, label_vector_row_num;
	double *samples, *labels;
	mxArray *instance_mat_col; // transposed instance sparse matrix

	prob.x = NULL;
	prob.y = NULL;
	x_space = NULL;

	// transpose instance matrix
	{
		mxArray *prhs[1], *plhs[1];
		prhs[0] = mxDuplicateArray(instance_mat);
		if(mexCallMATLAB(1, plhs, 1, prhs, "transpose"))
		{
			mexPrintf("Error: cannot transpose training instance matrix\n");
			return -1;
		}
		instance_mat_col = plhs[0];
		mxDestroyArray(prhs[0]);
	}

	// each column is one instance
	labels = mxGetPr(label_vec);
	samples = mxGetPr(instance_mat_col);
	ir = mxGetIr(instance_mat_col);
	jc = mxGetJc(instance_mat_col);

	num_samples = (int)mxGetNzmax(instance_mat_col);

	// the number of instance
	prob.l = (int)mxGetN(instance_mat_col);
	label_vector_row_num = (int)mxGetM(label_vec);

	if(label_vector_row_num!=prob.l)
	{
		mexPrintf("Length of label vector does not match # of instances.\n");
		return -1;
	}

	elements = num_samples + prob.l;
	max_index = (int)mxGetM(instance_mat_col);

	prob.y = Malloc(double,prob.l);
	prob.x = Malloc(struct svm_node *,prob.l);
	x_space = Malloc(struct svm_node, elements);

	j = 0;
	for(i=0;i<prob.l;i++)
	{
		prob.x[i] = &x_space[j];
		prob.y[i] = labels[i];
		low = (int)jc[i], high = (int)jc[i+1];
		for(k=low;k<high;k++)
		{
			x_space[j].index = (int)ir[k] + 1;
			x_space[j].value = samples[k];
			j++;
	 	}
		x_space[j++].index = -1;
	}

	if(param.gamma == 0 && max_index > 0)
		param.gamma = 1.0/max_index;

	return 0;
}
示例#29
0
void do_predict(mxArray *plhs[], const mxArray *prhs[], struct model *model_, const int predict_probability_flag)
{
	int label_vector_row_num, label_vector_col_num;
	int feature_number, testing_instance_number;
	int instance_index;
	double *ptr_label, *ptr_predict_label;
	double *ptr_prob_estimates, *ptr_dec_values, *ptr;
	struct feature_node *x;
	mxArray *pplhs[1]; // instance sparse matrix in row format

	int correct = 0;
	int total = 0;
	double error = 0;
	double sump = 0, sumt = 0, sumpp = 0, sumtt = 0, sumpt = 0;

	int nr_class=get_nr_class(model_);
	int nr_w;
	double *prob_estimates=NULL;

	if(nr_class==2 && model_->param.solver_type!=MCSVM_CS)
		nr_w=1;
	else
		nr_w=nr_class;

	// prhs[1] = testing instance matrix
	feature_number = get_nr_feature(model_);
	testing_instance_number = (int) mxGetM(prhs[1]);
	if(col_format_flag)
	{
		feature_number = (int) mxGetM(prhs[1]);
		testing_instance_number = (int) mxGetN(prhs[1]);
	}

	label_vector_row_num = (int) mxGetM(prhs[0]);
	label_vector_col_num = (int) mxGetN(prhs[0]);

	if(label_vector_row_num!=testing_instance_number)
	{
		mexPrintf("Length of label vector does not match # of instances.\n");
		fake_answer(plhs);
		return;
	}
	if(label_vector_col_num!=1)
	{
		mexPrintf("label (1st argument) should be a vector (# of column is 1).\n");
		fake_answer(plhs);
		return;
	}

	ptr_label    = mxGetPr(prhs[0]);

	// transpose instance matrix
	if(col_format_flag)
		pplhs[0] = (mxArray *)prhs[1];
	else
	{
		mxArray *pprhs[1];
		pprhs[0] = mxDuplicateArray(prhs[1]);
		if(mexCallMATLAB(1, pplhs, 1, pprhs, "transpose"))
		{
			mexPrintf("Error: cannot transpose testing instance matrix\n");
			fake_answer(plhs);
			return;
		}
	}


	prob_estimates = Malloc(double, nr_class);

	plhs[0] = mxCreateDoubleMatrix(testing_instance_number, 1, mxREAL);
	if(predict_probability_flag)
		plhs[2] = mxCreateDoubleMatrix(testing_instance_number, nr_class, mxREAL);
	else
		plhs[2] = mxCreateDoubleMatrix(testing_instance_number, nr_w, mxREAL);

	ptr_predict_label = mxGetPr(plhs[0]);
	ptr_prob_estimates = mxGetPr(plhs[2]);
	ptr_dec_values = mxGetPr(plhs[2]);
	x = Malloc(struct feature_node, feature_number+2);
	for(instance_index=0;instance_index<testing_instance_number;instance_index++)
	{
		int i;
		double target_label, predict_label;

		target_label = ptr_label[instance_index];

		// prhs[1] and prhs[1]^T are sparse
		read_sparse_instance(pplhs[0], instance_index, x, feature_number, model_->bias);

		if(predict_probability_flag)
		{
			predict_label = predict_probability(model_, x, prob_estimates);
			ptr_predict_label[instance_index] = predict_label;
			for(i=0;i<nr_class;i++)
				ptr_prob_estimates[instance_index + i * testing_instance_number] = prob_estimates[i];
		}
		else
		{
			double *dec_values = Malloc(double, nr_class);
			predict_label = predict_values(model_, x, dec_values);
			ptr_predict_label[instance_index] = predict_label;

			for(i=0;i<nr_w;i++)
				ptr_dec_values[instance_index + i * testing_instance_number] = dec_values[i];
			free(dec_values);
		}

		if(predict_label == target_label)
			++correct;
		error += (predict_label-target_label)*(predict_label-target_label);
		sump += predict_label;
		sumt += target_label;
		sumpp += predict_label*predict_label;
		sumtt += target_label*target_label;
		sumpt += predict_label*target_label;

		++total;
	}
	
	if(model_->param.solver_type==L2R_L2LOSS_SVR || 
           model_->param.solver_type==L2R_L1LOSS_SVR_DUAL || 
           model_->param.solver_type==L2R_L2LOSS_SVR_DUAL)
        {
                mexPrintf("Mean squared error = %g (regression)\n",error/total);
                mexPrintf("Squared correlation coefficient = %g (regression)\n",
                       ((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
                       ((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt))
                       );
        }
	//else
		//mexPrintf("Accuracy = %g%% (%d/%d)\n", (double) correct/total*100,correct,total);

	// return accuracy, mean squared error, squared correlation coefficient
	plhs[1] = mxCreateDoubleMatrix(3, 1, mxREAL);
	ptr = mxGetPr(plhs[1]);
	ptr[0] = (double)correct/total*100;
	ptr[1] = error/total;
	ptr[2] = ((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
				((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt));

	free(x);
	if(prob_estimates != NULL)
		free(prob_estimates);
}
示例#30
0
void predict(mxArray *plhs[], const mxArray *prhs[], struct svm_model *model, const int predict_probability)
{
	int label_vector_row_num, label_vector_col_num;
	int feature_number, testing_instance_number;
	int instance_index;
	double *ptr_instance, *ptr_label, *ptr_predict_label; 
	double *ptr_prob_estimates, *ptr_dec_values, *ptr;
	struct svm_node *x;
	mxArray *pplhs[1]; // transposed instance sparse matrix

	int correct = 0;
	int total = 0;
	double error = 0;
	double sump = 0, sumt = 0, sumpp = 0, sumtt = 0, sumpt = 0;

	int svm_type=svm_get_svm_type(model);
	int nr_class=svm_get_nr_class(model);
	double *prob_estimates=NULL;

	// prhs[1] = testing instance matrix
	feature_number = (int)mxGetN(prhs[1]);
	testing_instance_number = (int)mxGetM(prhs[1]);
	label_vector_row_num = (int)mxGetM(prhs[0]);
	label_vector_col_num = (int)mxGetN(prhs[0]);

	if(label_vector_row_num!=testing_instance_number)
	{
		mexPrintf("Length of label vector does not match # of instances.\n");
		fake_answer(plhs);
		return;
	}
	if(label_vector_col_num!=1)
	{
		mexPrintf("label (1st argument) should be a vector (# of column is 1).\n");
		fake_answer(plhs);
		return;
	}

	ptr_instance = mxGetPr(prhs[1]);
	ptr_label    = mxGetPr(prhs[0]);

	// transpose instance matrix
	if(mxIsSparse(prhs[1]))
	{
		if(model->param.kernel_type == PRECOMPUTED)
		{
			// precomputed kernel requires dense matrix, so we make one
			mxArray *rhs[1], *lhs[1];
			rhs[0] = mxDuplicateArray(prhs[1]);
			if(mexCallMATLAB(1, lhs, 1, rhs, "full"))
			{
				mexPrintf("Error: cannot full testing instance matrix\n");
				fake_answer(plhs);
				return;
			}
			ptr_instance = mxGetPr(lhs[0]);
			mxDestroyArray(rhs[0]);
		}
		else
		{
			mxArray *pprhs[1];
			pprhs[0] = mxDuplicateArray(prhs[1]);
			if(mexCallMATLAB(1, pplhs, 1, pprhs, "transpose"))
			{
				mexPrintf("Error: cannot transpose testing instance matrix\n");
				fake_answer(plhs);
				return;
			}
		}
	}

	if(predict_probability)
	{
		if(svm_type==NU_SVR || svm_type==EPSILON_SVR)
			mexPrintf("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model));
		else
			prob_estimates = (double *) malloc(nr_class*sizeof(double));
	}

	plhs[0] = mxCreateDoubleMatrix(testing_instance_number, 1, mxREAL);
	if(predict_probability)
	{
		// prob estimates are in plhs[2]
		if(svm_type==C_SVC || svm_type==NU_SVC)
			plhs[2] = mxCreateDoubleMatrix(testing_instance_number, nr_class, mxREAL);
		else
			plhs[2] = mxCreateDoubleMatrix(0, 0, mxREAL);
	}
	else
	{
		// decision values are in plhs[2]
		if(svm_type == ONE_CLASS ||
		   svm_type == EPSILON_SVR ||
		   svm_type == NU_SVR)
			plhs[2] = mxCreateDoubleMatrix(testing_instance_number, 1, mxREAL);
		else
			plhs[2] = mxCreateDoubleMatrix(testing_instance_number, nr_class*(nr_class-1)/2, mxREAL);
	}

	ptr_predict_label = mxGetPr(plhs[0]);
	ptr_prob_estimates = mxGetPr(plhs[2]);
	ptr_dec_values = mxGetPr(plhs[2]);
	x = (struct svm_node*)malloc((feature_number+1)*sizeof(struct svm_node) );
	for(instance_index=0;instance_index<testing_instance_number;instance_index++)
	{
		int i;
		double target_label, predict_label;

		target_label = ptr_label[instance_index];

		if(mxIsSparse(prhs[1]) && model->param.kernel_type != PRECOMPUTED) // prhs[1]^T is still sparse
			read_sparse_instance(pplhs[0], instance_index, x);
		else
		{
			for(i=0;i<feature_number;i++)
			{
				x[i].index = i+1;
				x[i].value = ptr_instance[testing_instance_number*i+instance_index];
			}
			x[feature_number].index = -1;
		}

		if(predict_probability)
		{
			if(svm_type==C_SVC || svm_type==NU_SVC)
			{
				predict_label = svm_predict_probability(model, x, prob_estimates);
				ptr_predict_label[instance_index] = predict_label;
				for(i=0;i<nr_class;i++)
					ptr_prob_estimates[instance_index + i * testing_instance_number] = prob_estimates[i];
			} else {
				predict_label = svm_predict(model,x);
				ptr_predict_label[instance_index] = predict_label;
			}
		}
		else
		{
			predict_label = svm_predict(model,x);
			ptr_predict_label[instance_index] = predict_label;

			if(svm_type == ONE_CLASS ||
			   svm_type == EPSILON_SVR ||
			   svm_type == NU_SVR)
			{
				double res;
				svm_predict_values(model, x, &res);
				ptr_dec_values[instance_index] = res;
			}
			else
			{
				double *dec_values = (double *) malloc(sizeof(double) * nr_class*(nr_class-1)/2);
				svm_predict_values(model, x, dec_values);
				for(i=0;i<(nr_class*(nr_class-1))/2;i++)
					ptr_dec_values[instance_index + i * testing_instance_number] = dec_values[i];
				free(dec_values);
			}
		}

		if(predict_label == target_label)
			++correct;
		error += (predict_label-target_label)*(predict_label-target_label);
		sump += predict_label;
		sumt += target_label;
		sumpp += predict_label*predict_label;
		sumtt += target_label*target_label;
		sumpt += predict_label*target_label;
		++total;
	}
	if(svm_type==NU_SVR || svm_type==EPSILON_SVR)
	{
		mexPrintf("Mean squared error = %g (regression)\n",error/total);
		mexPrintf("Squared correlation coefficient = %g (regression)\n",
			((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
			((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt))
			);
	}
	/* else */
	/*   mexPrintf("Accuracy = %g%% (%d/%d) (classification)\n", */
	/* 	    (double)correct/total*100,correct,total); */

	// return accuracy, mean squared error, squared correlation coefficient
	plhs[1] = mxCreateDoubleMatrix(3, 1, mxREAL);
	ptr = mxGetPr(plhs[1]);
	ptr[0] = (double)correct/total*100;
	ptr[1] = error/total;
	ptr[2] = ((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
				((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt));

	free(x);
	if(prob_estimates != NULL)
		free(prob_estimates);
}