コード例 #1
0
ファイル: cmex.c プロジェクト: AMFIRNAS/wso2-gridlabd
static MODULE *find_module(mxArray *handle)
{
	unsigned int64 *data = (unsigned int64*)mxGetPr(handle);
	return data[0]==MH_MODULE ? (MODULE*)data[1] : NULL;
}
コード例 #2
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])

{
	
	register int m, n, state, N, P, direct;
	
	register double *rle, *X, *T;
		
	//-----------------------
	// INPUT
	//-----------------------

	//--
	// run-length code
	//--
	
	rle = mxGetPr(prhs[0]);

	// size of image

	m = *(rle);

	n = *(rle + 1);

	// initial state of decoder

	state = (int) *(rle + 2);

	// run-length encoding

	rle = rle + 3;

	N = mxGetM(prhs[0]) * mxGetN(prhs[0]) - 3;
	
	//-----------------------
	// OUTPUT 
	//-----------------------

	// decoded image
	
	X = mxGetPr(plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL));
  	
	//--
	// COMPUTATION
	//--

	if (nrhs < 2) {
		
		//--
		// run-length decode
		//--
		
		rle_decode (X, state, rle, N);
		
	} else {
		
		//--
		// get label table and table type
		//--
		
		T = mxGetPr(prhs[1]);
		
		P = mxGetM(prhs[1]) * mxGetN(prhs[1]);
		
		direct = (int) mxGetScalar(prhs[2]);
		
		// check length of table if each run has a direct label
		
		if (direct && (N != P)) {
			mexErrMsgTxt("Table length must match run-length code length.");
		}
		
		//--
		// run-length decoding and labelling
		//--
		
		if (direct) {
			rle_decode_label(X, state, rle, N, T, 0);
		} else {
			rle_decode_label(X, state, rle, N, T, P);
		}
		
	}
		
}
コード例 #3
0
ファイル: mexTrainDL.cpp プロジェクト: 23119841/ihog
   inline void callFunction(mxArray* plhs[], const mxArray*prhs[],
         const long nlhs,const long nrhs) {
      if (!mexCheckType<T>(prhs[0])) 
         mexErrMsgTxt("type of argument 1 is not consistent");

      if (!mxIsStruct(prhs[1])) 
         mexErrMsgTxt("argument 2 should be struct");

      if (nrhs == 3)
         if (!mxIsStruct(prhs[2])) 
            mexErrMsgTxt("argument 3 should be struct");

      Data<T> *X;
      const mwSize* dimsX=mxGetDimensions(prhs[0]);
      long n=static_cast<long>(dimsX[0]);
      long M=static_cast<long>(dimsX[1]);
      if (mxIsSparse(prhs[0])) {
         double * X_v=static_cast<double*>(mxGetPr(prhs[0]));
         mwSize* X_r=mxGetIr(prhs[0]);
         mwSize* X_pB=mxGetJc(prhs[0]);
         mwSize* X_pE=X_pB+1;
         long* X_r2, *X_pB2, *X_pE2;
         T* X_v2;
         createCopySparse<T>(X_v2,X_r2,X_pB2,X_pE2,
               X_v,X_r,X_pB,X_pE,M);
         X = new SpMatrix<T>(X_v2,X_r2,X_pB2,X_pE2,n,M,X_pB2[M]);
      } else {
         T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
         X= new Matrix<T>(prX,n,M);
      }

      long NUM_THREADS = getScalarStructDef<long>(prhs[1],"numThreads",-1);
#ifdef _OPENMP
      NUM_THREADS = NUM_THREADS == -1 ? omp_get_num_procs() : NUM_THREADS;
#else
      NUM_THREADS=1;
#endif 
      long batch_size = getScalarStructDef<long>(prhs[1],"batchsize",
            256*(NUM_THREADS+1));
      mxArray* pr_D = mxGetField(prhs[1],0,"D");
      Trainer<T>* trainer;

      if (!pr_D) {
         long K = getScalarStruct<long>(prhs[1],"K");
         trainer = new Trainer<T>(K,batch_size,NUM_THREADS);
      } else {
         T* prD = reinterpret_cast<T*>(mxGetPr(pr_D));
         const mwSize* dimsD=mxGetDimensions(pr_D);
         long nD=static_cast<long>(dimsD[0]);
         long K=static_cast<long>(dimsD[1]);
         if (n != nD) mexErrMsgTxt("sizes of D are not consistent");
         Matrix<T> D1(prD,n,K);
         if (nrhs == 3) {
            mxArray* pr_A = mxGetField(prhs[2],0,"A");
            if (!pr_A) mexErrMsgTxt("field A is not provided");
            T* prA = reinterpret_cast<T*>(mxGetPr(pr_A));
            const mwSize* dimsA=mxGetDimensions(pr_A);
            long xA=static_cast<long>(dimsA[0]);
            long yA=static_cast<long>(dimsA[1]);
            if (xA != K || yA != K) mexErrMsgTxt("Size of A is not consistent");
            Matrix<T> A(prA,K,K);

            mxArray* pr_B = mxGetField(prhs[2],0,"B");
            if (!pr_B) mexErrMsgTxt("field B is not provided");
            T* prB = reinterpret_cast<T*>(mxGetPr(pr_B));
            const mwSize* dimsB=mxGetDimensions(pr_B);
            long xB=static_cast<long>(dimsB[0]);
            long yB=static_cast<long>(dimsB[1]);
            if (xB != n || yB != K) mexErrMsgTxt("Size of B is not consistent");
            Matrix<T> B(prB,n,K);
            long iter = getScalarStruct<long>(prhs[2],"iter");
            trainer = new Trainer<T>(A,B,D1,iter,batch_size,NUM_THREADS);
         } else {
            trainer = new Trainer<T>(D1,batch_size,NUM_THREADS);
         }
      }

      ParamDictLearn<T> param;
      param.lambda = getScalarStruct<T>(prhs[1],"lambda");
      param.lambda2 = getScalarStructDef<T>(prhs[1],"lambda2",10e-10);
      param.iter=getScalarStruct<long>(prhs[1],"iter");
      param.t0 = getScalarStructDef<T>(prhs[1],"t0",1e-5);
      param.mode =(constraint_type)getScalarStructDef<long>(prhs[1],"mode",PENALTY);
      param.posAlpha = getScalarStructDef<bool>(prhs[1],"posAlpha",false);
      param.posD = getScalarStructDef<bool>(prhs[1],"posD",false);
      param.expand= getScalarStructDef<bool>(prhs[1],"expand",false);
      param.modeD=(constraint_type_D)getScalarStructDef<long>(prhs[1],"modeD",L2);
      param.whiten = getScalarStructDef<bool>(prhs[1],"whiten",false);
      param.clean = getScalarStructDef<bool>(prhs[1],"clean",true);
      param.verbose = getScalarStructDef<bool>(prhs[1],"verbose",true);
      param.gamma1 = getScalarStructDef<T>(prhs[1],"gamma1",0);
      param.gamma2 = getScalarStructDef<T>(prhs[1],"gamma2",0);
      param.rho = getScalarStructDef<T>(prhs[1],"rho",T(1.0));
      param.stochastic = 
         getScalarStructDef<bool>(prhs[1],"stochastic_deprecated",
               false);
      param.modeParam = static_cast<mode_compute>(getScalarStructDef<long>(prhs[1],"modeParam",0));
      param.batch = getScalarStructDef<bool>(prhs[1],"batch",false);
      param.iter_updateD = getScalarStructDef<T>(prhs[1],"iter_updateD",param.batch ? 5 : 1);
      param.log = getScalarStructDef<bool>(prhs[1],"log_deprecated",
            false);
      if (param.log) {
         mxArray *stringData = mxGetField(prhs[1],0,
               "logName_deprecated");
         if (!stringData) 
            mexErrMsgTxt("Missing field logName_deprecated");
         long stringLength = mxGetN(stringData)+1;
         param.logName= new char[stringLength];
         mxGetString(stringData,param.logName,stringLength);
      }

      trainer->train(*X,param);
      if (param.log)
         mxFree(param.logName);

      Matrix<T> D;
      trainer->getD(D);
      long K  = D.n();
      plhs[0] = createMatrix<T>(n,K);
      T* prD2 = reinterpret_cast<T*>(mxGetPr(plhs[0]));
      Matrix<T> D2(prD2,n,K);
      D2.copy(D);

      if (nlhs == 2) {
         mwSize dims[1] = {1};
         long nfields=3; 
         const char *names[] = {"A", "B", "iter"};
         plhs[1]=mxCreateStructArray(1, dims,nfields, names);
         mxArray* prA = createMatrix<T>(K,K);
         T* pr_A= reinterpret_cast<T*>(mxGetPr(prA));
         Matrix<T> A(pr_A,K,K);
         trainer->getA(A);
         mxSetField(plhs[1],0,"A",prA);
         mxArray* prB = createMatrix<T>(n,K);
         T* pr_B= reinterpret_cast<T*>(mxGetPr(prB));
         Matrix<T> B(pr_B,n,K);
         trainer->getB(B);
         mxSetField(plhs[1],0,"B",prB);
         mxArray* priter = createScalar<T>();
         *mxGetPr(priter) = static_cast<T>(trainer->getIter());
         mxSetField(plhs[1],0,"iter",priter);
      }
      delete(trainer);
      delete(X);
   }
コード例 #4
0
/* The matlab mex function */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    /* All inputs */
    double *FacesA, *FacesB, *FacesC, *VerticesX, *VerticesY, *VerticesZ;
    double *Iterations, *Lambda;
    /* All outputs */
    double *VerticesOX, *VerticesOY, *VerticesOZ;

    /* All outputs, Vertex storage*/
    double *VerticesNX, *VerticesNY, *VerticesNZ;
    double *VerticesN2X, *VerticesN2Y, *VerticesN2Z;
    
        
    /* Temporary Weights */
    double *VerticesW ;
    
    /* Number of faces */
    const mwSize *FacesDims;
    int FacesN=0;
   
    /* Number of vertices */
    const mwSize *VertexDims;
    int VertexN=0;
    int VertexNA[1]={0};    
    
    /* Point Update temporary storage */
    double Ux, Uy, Uz;
    
    /* 1D Index  */
    int index0, index1, index2;
            
    /* Edge coordinates and lenght */
    double e0x, e0y, e0z, e0l;
    double e1x, e1y, e1z, e1l;
    double e2x, e2y, e2z, e2l;
    
    /* Swap point variable */
    double *t;
    int swap=0;
    
    /* Loop variable */
    int i,j;
            
    /* Check for proper number of arguments. */
   if(nrhs!=8) {
     mexErrMsgTxt("8 inputs are required.");
   } else if(nlhs!=3) {
     mexErrMsgTxt("3 outputs are required");
   }
   
   /* Read all inputs (faces and vertices) */
   FacesA=mxGetPr(prhs[0]);
   FacesB=mxGetPr(prhs[1]);
   FacesC=mxGetPr(prhs[2]);
   VerticesX=mxGetPr(prhs[3]);
   VerticesY=mxGetPr(prhs[4]);
   VerticesZ=mxGetPr(prhs[5]);
   Iterations=mxGetPr(prhs[6]);
   Lambda=mxGetPr(prhs[7]);
   /* Get number of FacesN */
   FacesDims = mxGetDimensions(prhs[0]);   
   FacesN=FacesDims[0]*FacesDims[1];
   
   /* Get number of VertexN */
   VertexDims = mxGetDimensions(prhs[3]);   
   VertexN=VertexDims[0]*VertexDims[1];
   
   /* Intern vertices storage */
   VerticesW = (double *)malloc( VertexN * sizeof(double) );
   VerticesNX = (double *)malloc( VertexN * sizeof(double) );
   VerticesNY = (double *)malloc( VertexN * sizeof(double) );
   VerticesNZ = (double *)malloc( VertexN * sizeof(double) );
   VerticesN2X = (double *)malloc( VertexN * sizeof(double) );
   VerticesN2Y = (double *)malloc( VertexN * sizeof(double) );
   VerticesN2Z = (double *)malloc( VertexN * sizeof(double) );
   
   /* Copy input arrays to ouput vertice arrays */
   memcpy( VerticesNX,VerticesX,VertexN* sizeof(double));
   memcpy( VerticesNY,VerticesY,VertexN* sizeof(double));
   memcpy( VerticesNZ,VerticesZ,VertexN* sizeof(double));
   
   for (j=0; j<Iterations[0]; j++)
   {
       /* Clean the weights */
       for (i=0; i<VertexN; i++) { VerticesW[i] =0;  VerticesN2X[i]=0; VerticesN2Y[i]=0; VerticesN2Z[i]=0; }

       /* Calculate all face normals and angles */
       for (i=0; i<FacesN; i++)
       {
           /* Get indices of face vertices */
           index0=(int)FacesA[i]-1;
           index1=(int)FacesB[i]-1;
           index2=(int)FacesC[i]-1;

           /* Calculate edge lengths */
           e0x=VerticesNX[index0]-VerticesNX[index1];  
           e0y=VerticesNY[index0]-VerticesNY[index1];  
           e0z=VerticesNZ[index0]-VerticesNZ[index1];
           e1x=VerticesNX[index1]-VerticesNX[index2];  
           e1y=VerticesNY[index1]-VerticesNY[index2];  
           e1z=VerticesNZ[index1]-VerticesNZ[index2];
           e2x=VerticesNX[index2]-VerticesNX[index0];  
           e2y=VerticesNY[index2]-VerticesNY[index0];  
           e2z=VerticesNZ[index2]-VerticesNZ[index0];
           e0l=1 / (sqrt(e0x*e0x + e0y*e0y + e0z*e0z)+Lambda[1]);
           e1l=1 / (sqrt(e1x*e1x + e1y*e1y + e1z*e1z)+Lambda[1]);
           e2l=1 / (sqrt(e2x*e2x + e2y*e2y + e2z*e2z)+Lambda[1]);

           VerticesN2X[index0]+=VerticesNX[index1]*e0l;
           VerticesN2Y[index0]+=VerticesNY[index1]*e0l;
           VerticesN2Z[index0]+=VerticesNZ[index1]*e0l;
           VerticesW[index0]+=e0l;

           VerticesN2X[index1]+=VerticesNX[index0]*e0l; 
           VerticesN2Y[index1]+=VerticesNY[index0]*e0l;
           VerticesN2Z[index1]+=VerticesNZ[index0]*e0l;
           VerticesW[index1]+=e0l;


           VerticesN2X[index1]+=VerticesNX[index2]*e1l;
           VerticesN2Y[index1]+=VerticesNY[index2]*e1l;
           VerticesN2Z[index1]+=VerticesNZ[index2]*e1l;
           VerticesW[index1]+=e1l;

           VerticesN2X[index2]+=VerticesNX[index1]*e1l;
           VerticesN2Y[index2]+=VerticesNY[index1]*e1l;
           VerticesN2Z[index2]+=VerticesNZ[index1]*e1l;
           VerticesW[index2]+=e1l;

           VerticesN2X[index2]+=VerticesNX[index0]*e2l;
           VerticesN2Y[index2]+=VerticesNY[index0]*e2l; 
           VerticesN2Z[index2]+=VerticesNZ[index0]*e2l;
           VerticesW[index2]+=e2l;

           VerticesN2X[index0]+=VerticesNX[index2]*e2l; 
           VerticesN2Y[index0]+=VerticesNY[index2]*e2l; 
           VerticesN2Z[index0]+=VerticesNZ[index2]*e2l;
           VerticesW[index0]+=e2l;
       }

       /* Normalize the Vertices */
       for (i=0; i<VertexN; i++)
       {
           Ux=0; Uy=0; Uz=0;
           Ux=VerticesN2X[i]/VerticesW[i];
           Uy=VerticesN2Y[i]/VerticesW[i];
           Uz=VerticesN2Z[i]/VerticesW[i];

           Ux=Ux-VerticesNX[i]; 
           Uy=Uy-VerticesNY[i]; 
           Uz=Uz-VerticesNZ[i]; 

           VerticesN2X[i]=VerticesNX[i]+Ux*Lambda[0]; 
           VerticesN2Y[i]=VerticesNY[i]+Uy*Lambda[0]; 
           VerticesN2Z[i]=VerticesNZ[i]+Uz*Lambda[0];
       }
       
       /* Swap the variables */
       t=VerticesNX; VerticesNX=VerticesN2X; VerticesN2X=t;
       t=VerticesNY; VerticesNY=VerticesN2Y; VerticesN2Y=t;
       t=VerticesNZ; VerticesNZ=VerticesN2Z; VerticesN2Z=t;

       /* Swap output variable */
       if(swap==0) { swap=1; } else { swap=0; }
   }

   /* Create Output arrays for the new vertex coordinates */
   VertexNA[0]=VertexN;
   plhs[0] = mxCreateNumericArray(1, VertexNA, mxDOUBLE_CLASS, mxREAL);
   plhs[1] = mxCreateNumericArray(1, VertexNA, mxDOUBLE_CLASS, mxREAL);
   plhs[2] = mxCreateNumericArray(1, VertexNA, mxDOUBLE_CLASS, mxREAL);
   VerticesOX = mxGetPr(plhs[0]);
   VerticesOY=  mxGetPr(plhs[1]);
   VerticesOZ = mxGetPr(plhs[2]);

   if(swap==0)
   {
        /* Copy input arrays to ouput vertice arrays */
       memcpy( VerticesOX,VerticesN2X,VertexN* sizeof(double));
       memcpy( VerticesOY,VerticesN2Y,VertexN* sizeof(double));
       memcpy( VerticesOZ,VerticesN2Z,VertexN* sizeof(double));
   }
   else
   {
        /* Copy input arrays to ouput vertice arrays */
       memcpy( VerticesOX,VerticesNX,VertexN* sizeof(double));
       memcpy( VerticesOY,VerticesNY,VertexN* sizeof(double));
       memcpy( VerticesOZ,VerticesNZ,VertexN* sizeof(double));
   }
           
   
   /* Free memory */
   free(VerticesW);
   free(VerticesNX);
   free(VerticesNY);
   free(VerticesNZ);
   
   free(VerticesN2X);
   free(VerticesN2Y);
   free(VerticesN2Z);
}
コード例 #5
0
ファイル: psdframeit.c プロジェクト: huwenboshi/wqe
/* ************************************************************
   PROCEDURE mexFunction - Entry for Matlab
   ************************************************************ */
void mexFunction(const int nlhs, mxArray *plhs[],
                 const int nrhs, const mxArray *prhs[])
{
    mwIndex i,lendiag, lenfull, lenud,qsize;
    double *x, *fwork;
    const double *lab,*frms;
    mwIndex *sdpNL;
    coneK cK;
    /* ------------------------------------------------------------
       Check for proper number of arguments
       ------------------------------------------------------------ */
    mxAssert(nrhs >= NPARIN, "psdframeit requires more input arguments.");
    mxAssert(nlhs <= NPAROUT, "psdframeit generates less output arguments.");
    /* ------------------------------------------------------------
       Disassemble cone K structure
       ------------------------------------------------------------ */
    conepars(K_IN, &cK);
    /* ------------------------------------------------------------
       Get statistics of cone K structure
       ------------------------------------------------------------ */
    lenud = cK.rDim + cK.hDim;
    qsize = lenud + cK.hLen;
    lenfull = cK.lpN +  cK.qDim + lenud;
    lendiag = cK.lpN + 2 * cK.lorN + cK.rLen + cK.hLen;
    /* ------------------------------------------------------------
       Get inputs lab,frms
       ------------------------------------------------------------ */
    lab = mxGetPr(LAB_IN);
    if(mxGetM(LAB_IN) * mxGetN(LAB_IN) != cK.rLen + cK.hLen) {
        mxAssert(mxGetM(LAB_IN) * mxGetN(LAB_IN) == lendiag, "lab size mismatch");
        lab += cK.lpN + 2 * cK.lorN;
    }
    mxAssert(mxGetM(FRMS_IN) * mxGetN(FRMS_IN) == qsize, "frms size mismatch");
    frms = mxGetPr(FRMS_IN);
    /* ------------------------------------------------------------
       Allocate output x
       ------------------------------------------------------------ */
    X_OUT =  mxCreateDoubleMatrix(lenud, (mwSize)1, mxREAL);
    x = mxGetPr(X_OUT);
    /* ------------------------------------------------------------
       Allocate working array fwork(max(rmaxn,2*hmaxn))
       integer working array sdpNL(sdpN).
       ------------------------------------------------------------ */
    fwork = (double *) mxCalloc(MAX(1,MAX(cK.rMaxn,2*cK.hMaxn)),sizeof(double));
    sdpNL = (mwIndex *) mxCalloc(MAX(1,cK.sdpN), sizeof(mwIndex));
    /* ------------------------------------------------------------
       double to integer
       ------------------------------------------------------------ */
    for(i = 0; i < cK.sdpN; i++)
        sdpNL[i] = cK.sdpNL[i];
    /* ------------------------------------------------------------
       PSD: X = Qb' * diag(lab) * Qb,          Qb = Q_1*Q_2*..*Q_{n-1}
       where Q_k = I-ck*ck'/betak is an elementary Householder reflection.
       Format: frms = [c1, .., c_{n-1}, beta].
       VERY INEFFICIENT !!!!
       ------------------------------------------------------------ */
    psdframeit(x, frms,lab,sdpNL,cK.rsdpN,cK.sdpN,fwork);
    /* ------------------------------------------------------------
       Release working array
       ------------------------------------------------------------ */
    mxFree(sdpNL);
    mxFree(fwork);
}
コード例 #6
0
void mexFunction(
    int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[]
)
{
  int display=0, i=0;
  long *lpenv=NULL ;
  CPXENVptr     env = NULL;
  int           status ;
  double value ;
  char param_name[128] ;
  int param_code=-1, dblfound=0, strfound=0 ;
  
  if (nrhs > 7 || nrhs < 1) {
    mexErrMsgTxt("Usage: [how] "
		 "= lp_set_param(lpenv, param_name, value, display)");
    return;
  }
  switch (nrhs) {
  case 4:
    if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) {
      if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) 
	  ||  mxIsSparse(prhs[3])
	  || !(mxGetM(prhs[3])==1 && mxGetN(prhs[3])==1)) {
	mexErrMsgTxt("4th argument (display) must be "
		     "an integer scalar.");
	return;
      }
      display = *mxGetPr(prhs[3]);
    }
  case 3:
    if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) {
      if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) 
	  ||  mxIsSparse(prhs[2])
	  || !(mxGetM(prhs[2])==1 && mxGetN(prhs[2])==1)) {
	mexErrMsgTxt("3rd argument (value) must be "
		     "an integer scalar.");
	return;
      }
      value = *mxGetPr(prhs[2]);
    }
  case 2:
    if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) {
      if (mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) 
	  ||  mxIsSparse(prhs[1]) || !mxIsChar(prhs[1])
	  || !(mxGetM(prhs[1])==1) && mxGetN(prhs[1])>=1) {
	mexErrMsgTxt("2nd argument (param) must be "
		     "a string.");
	return;
      }
      mxGetString(prhs[1], param_name, 128);
    }
  case 1:
    if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) {
      if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) 
	  ||  mxIsSparse(prhs[0])
	  || !mxIsDouble(prhs[0]) 
	  ||  mxGetN(prhs[0])!=1 ) {
	mexErrMsgTxt("1st argument (lpenv) must be "
		     "a column vector.");
	return;
      }
      if (1 != mxGetM(prhs[0])) {
	mexErrMsgTxt("Dimension error (arg 1).");
	return;
      }
      lpenv = (long*) mxGetPr(prhs[0]);
    }
  }
  
  if (nlhs > 1 || nlhs < 1) {
    mexErrMsgTxt("Usage: [how] "
		 "= lp_set_param(lpenv,param_name,value,disp)");
    return;
  }
  if (display>2) fprintf(STD_OUT, "argument processing finished\n") ;

  /* Initialize the CPLEX environment */
  env = (CPXENVptr) lpenv[0] ;

  for (i=0; i<NUM_PARAMS; i++)
      if (strcmp(param_info[i].name, param_name)==0)
	  param_code=param_info[i].code ;

  if (display>3) 
    fprintf(STD_OUT, "(param=%s(%i), value=%f) \n", param_name, param_code, value) ;
  if (param_code==-1)
    mxErrMsgTxt("illegal parameter name") ;

  for (i=0; i<NUM_DBLPARAMS; i++)
    if (param_code==dblParams[i])
      dblfound=1 ;
  for (i=0; i<NUM_STRPARAMS; i++)
    if (param_code==strParams[i])
      strfound=1 ;
  if (dblfound==1) {
    if (display>2) 
      fprintf(STD_OUT, "calling CPXsetdblparam\n") ;
    status = CPXsetdblparam(env, param_code, value);
    if ( status ) {
      fprintf (STD_OUT, "CPXsetdblparam failed.\n");
      goto TERMINATE;
    } 
  } else if (strfound==1)
  {
	  fprintf(STD_OUT, "sorry not implemented\n") ;
  } else {
    if (display>2) 
      fprintf(STD_OUT, "calling CPXsetintparam\n") ;
    status = CPXsetintparam(env, param_code, (int)value);
    if ( status ) {
      fprintf (STD_OUT, "CPXsetintparam failed.\n");
      goto TERMINATE;
    }
  } ;

 TERMINATE:
  if (status) {
    char  errmsg[1024];
    CPXgeterrorstring (env, status, errmsg);
    fprintf (STD_OUT, "%s", errmsg);
    if (nlhs >= 1) 
      plhs[0] = mxCreateString(errmsg) ;
  } else
    if (nlhs >= 1) 
      plhs[0] = mxCreateString("OK") ;
  ;
  return ;
} 
コード例 #7
0
ファイル: mexContour2Seg.cpp プロジェクト: fdsa1860/voc-dpm
mxArray *process(const mxArray *mx_X, const mxArray *mx_winSize)
{
    mwSize vel_diff_gap;
    mwSize winSize, velSize;
    mwSize m, n;
    mwSize nStruct_Y, nFields_Y;
    mxArray *mx_Y;
    mxArray *mx_seg_points, *mx_seg_vel, *mx_seg_loc;
    double *X;
    double *seg_points, *seg_vel, *seg_loc;
    mwIndex Y_points_fieldNum, Y_vel_fieldNum, Y_loc_fieldNum;
    mwIndex count;
    mwIndex iY, i, j;
    
    vel_diff_gap = 5;
    winSize = mxGetScalar(mx_winSize);
    m = mxGetM(mx_X);
    n = mxGetN(mx_X);
    velSize = winSize - vel_diff_gap + 1;
    nStruct_Y = m - winSize + 1;
    nFields_Y = 3;
    
    const char *fNames[nFields_Y];
    fNames[0] = "points";
    fNames[1] = "vel";
    fNames[2] = "loc";
    mx_Y = mxCreateStructMatrix(1, nStruct_Y, nFields_Y, fNames);
    
    Y_points_fieldNum = mxGetFieldNumber(mx_Y, "points");
    Y_vel_fieldNum = mxGetFieldNumber(mx_Y, "vel");
    Y_loc_fieldNum = mxGetFieldNumber(mx_Y, "loc");
    
    X = mxGetPr(mx_X);
    for (iY=0; iY<nStruct_Y; ++iY)
    {
        mx_seg_points = mxCreateDoubleMatrix(winSize, n, mxREAL);
        seg_points = mxGetPr(mx_seg_points);
        count = 0;
        for (j=0; j<n; ++j)
        {
            for (i=iY; i<iY+winSize; ++i)
            {
                seg_points[count++] = X[j*m+i];
            }
        }
        
        mx_seg_vel = mxCreateDoubleMatrix(velSize, n, mxREAL);
        seg_vel = mxGetPr(mx_seg_vel);
        count = 0;
        for (j=0; j<n; ++j)
        {
            for (i=0; i<velSize; ++i)
            {
                seg_vel[count++] = seg_points[j*winSize+i] - seg_points[j*winSize+i+vel_diff_gap-1];
            }
        }
        
        mx_seg_loc = mxCreateDoubleMatrix(1, 2, mxREAL);
        seg_loc = mxGetPr(mx_seg_loc);
        seg_loc[0] = seg_points[winSize+(winSize-1)/2];
        seg_loc[1] = seg_points[(winSize-1)/2];
        
        mxSetFieldByNumber(mx_Y, iY, Y_points_fieldNum, mx_seg_points);
        mxSetFieldByNumber(mx_Y, iY, Y_vel_fieldNum, mx_seg_vel);
        mxSetFieldByNumber(mx_Y, iY, Y_loc_fieldNum, mx_seg_loc);
    }
    return mx_Y;
}
コード例 #8
0
ファイル: DespikeOptimise.c プロジェクト: psy2013GitHub/Atom
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	double *data;
  int c=0;
  mxArray *mxout, *mxin, *mxstr;
  double *out;
  char *str;
  double *yfit;
  double median_tc,mad_res;
  double mad_res_array;
  struct fminestimate *estimate  

	data=mxGetPr(prhs[0]);
	nTp=mxGetM(data);
	nVox=mxGetN(data);
  
  mxout=mxCreateDoubleMatrix(1,1,mxREAL);
  out=mxGetPr(mxout);
  mxstr=mxCreateString("double");
  mexCallMatlab(1,mxout,0,mxstr,'REALMIN');
  REALMIN=*(mxGetPr(mxout));
  mxDestroyArray(mxout);
  mxDestroyArray(mxstr);
  
  yfit=malloc(sizeof(double)*nTp);
  tc=malloc(sizeof(double)*nTp);
  mad_res_array=malloc(sizeof(yfit));
  for(c=0;c<nVox;++c)
    {
      for(i=0;i<nTp;++i)
        *(tc+i)=*(data+nTp*c+i);

      ylerr=
      icatb_fun(xestimate, &yqerr, tc, TR);
      icatb_fun(xestimates,&yserr, tc, TR);
      //
      yerr=ylerr;
      miny=1;
      if(yerr>yqerr)
        miny=2;
      if(yerr>yserr)
        miny=3;
      //
      if(miny==1)
        yfit=[];
      else if(miny==2)
        icatb_quadFit(yfit,coff,nTp,TR);
      else if(miny==3)
        icatb_splFit(yfit,coff,nTp,TR);
      // residue
      for(i=0;i<nTp;++i)
        *(tc+i)-=*(yfit+i);
      quickSort(tc,rawOrder,0,nTp-1);
      median_tc=median(tc);
      for(i=0;i<nTp;++i)
        *(mad_res_array+i)=abs(*(tc+i)-median_tc);
      mad_res=median(mad_res_array);
      sigma=mad_res*pow(PI/2.0,0.5);
      for(i=0;i<nTp;++i)
        *(tc+i)=*(tc+i)/sigma;
      for(t=0;t<nTp;++t)
        if(abs(*(tc+t))>c1)
        {
          *(Data+nTp*c+t)=sign(*(tc+t)) * (c1+((c2-c1) * tanh((abs(*(tc+t)))-c1) / (c2-c1)));
          *(Data+nTp*c+t)=*(tc+t)*sigma + *(yfit+t);
        }
    }
コード例 #9
0
ファイル: c3_aircraft_2.c プロジェクト: tharunprasanth/DG_sim
mxArray *sf_c3_aircraft_2_get_autoinheritance_info(void)
{
  const char *autoinheritanceFields[] = { "checksum", "inputs", "parameters",
    "outputs", "locals", "postCodegenInfo" };

  mxArray *mxAutoinheritanceInfo = mxCreateStructMatrix(1, 1, sizeof
    (autoinheritanceFields)/sizeof(autoinheritanceFields[0]),
    autoinheritanceFields);

  {
    mxArray *mxChecksum = mxCreateString("l72N1h3tSuAH6udgIXwWtG");
    mxSetField(mxAutoinheritanceInfo,0,"checksum",mxChecksum);
  }

  {
    const char *dataFields[] = { "size", "type", "complexity" };

    mxArray *mxData = mxCreateStructMatrix(1,1,3,dataFields);

    {
      mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
      double *pr = mxGetPr(mxSize);
      pr[0] = (double)(1);
      pr[1] = (double)(1);
      mxSetField(mxData,0,"size",mxSize);
    }

    {
      const char *typeFields[] = { "base", "fixpt" };

      mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
      mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
      mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
      mxSetField(mxData,0,"type",mxType);
    }

    mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
    mxSetField(mxAutoinheritanceInfo,0,"inputs",mxData);
  }

  {
    mxSetField(mxAutoinheritanceInfo,0,"parameters",mxCreateDoubleMatrix(0,0,
                mxREAL));
  }

  {
    const char *dataFields[] = { "size", "type", "complexity" };

    mxArray *mxData = mxCreateStructMatrix(1,1,3,dataFields);

    {
      mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
      double *pr = mxGetPr(mxSize);
      pr[0] = (double)(1);
      pr[1] = (double)(1);
      mxSetField(mxData,0,"size",mxSize);
    }

    {
      const char *typeFields[] = { "base", "fixpt" };

      mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
      mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
      mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
      mxSetField(mxData,0,"type",mxType);
    }

    mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
    mxSetField(mxAutoinheritanceInfo,0,"outputs",mxData);
  }

  {
    mxSetField(mxAutoinheritanceInfo,0,"locals",mxCreateDoubleMatrix(0,0,mxREAL));
  }

  {
    mxArray* mxPostCodegenInfo = sf_c3_aircraft_2_get_post_codegen_info();
    mxSetField(mxAutoinheritanceInfo,0,"postCodegenInfo",mxPostCodegenInfo);
  }

  return(mxAutoinheritanceInfo);
}
コード例 #10
0
ファイル: length2strong_mex.c プロジェクト: parkmh/MATAMG
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    double *ia, *ja, *C;
    double *is2, *js2, *as2;
    double *inbd, *jnbd, *anbd;
    int m;
    int path;
    int *npath;
    int nbdindex, nbdsize;
    int *len2nbd, len2start;
    int index = 0;
    int i, j, k, jaj, jak,l;
    int isinnbd;
    
    if(nrhs!=4) {
        mexErrMsgIdAndTxt("MATAMG:length2strong:nrhs", "LENGTH2STRONG_MEX(IA,JA,IS,JS,AS,C,PATH)");
    }
    
    ia = mxGetPr(prhs[0]);
    ja = mxGetPr(prhs[1]);
        
    C = mxGetPr(prhs[2]);
    path =(int)mxGetScalar(prhs[3]);
    m = mxGetN(prhs[2]);
    npath = (int*)calloc(m,sizeof(int));
    int maxnnzrow = 0;
    
    for ( i = 1; i <= m; i++ ) {
        if ((int)(ia[ i ] - ia[ i - 1 ]) > maxnnzrow )
            maxnnzrow = (int)(ia[ i ] - ia[ i - 1 ]);
    }
    
    plhs[0] = mxCreateDoubleMatrix(maxnnzrow*maxnnzrow*m,1,mxREAL);
    plhs[1] = mxCreateDoubleMatrix(maxnnzrow*maxnnzrow*m,1,mxREAL);
    plhs[2] = mxCreateDoubleMatrix(maxnnzrow*maxnnzrow*m,1,mxREAL);
    plhs[3] = mxCreateDoubleMatrix(1,1,mxREAL);
    plhs[4] = mxCreateDoubleMatrix(m+1,1,mxREAL);
    plhs[5] = mxCreateDoubleMatrix(maxnnzrow*maxnnzrow*m,1,mxREAL);
    len2nbd = (int*)calloc(maxnnzrow*maxnnzrow,sizeof(int));
    
    is2 = mxGetPr(plhs[0]);
    js2 = mxGetPr(plhs[1]);
    as2 = mxGetPr(plhs[2]);
    inbd = mxGetPr(plhs[4]);
    jnbd = mxGetPr(plhs[5]);
    
    nbdindex = 0;    
    /* Compute length 2 connections */
    inbd[ 0 ] = 1;
    for ( i = 1; i <= m; i++ ) {
        nbdsize = 0;
        /* Check length 1 connections */
        for (j = (int)ia[ i - 1 ]; j < (int)ia[ i ]; j++){
            jaj = (int)ja[ j - 1];
            if (jaj!=i){
                len2nbd[nbdsize] = (int)ja[ j - 1 ];
                nbdsize++;
            }
        }
        len2start = nbdsize;
        /* Check length 2 connections */
        for (j = (int)ia[ i - 1 ]; j < (int)ia[ i ]; j++){
            jaj = (int)ja[ j - 1 ];
            if ( jaj != i ){
                for ( k = (int)ia[ jaj - 1 ]; k < (int)ia[ jaj ] ; k++ ){
                    isinnbd = 0;
                    jak =  (int)ja[ k - 1 ];
                    if (jak != i && jak != jaj){
                        for ( l = 0; l < nbdsize; l++ ) {
                            if ( len2nbd[ l ] == jak ){
                                isinnbd = 1;
                                break;
                            }
                        }
                        if (!isinnbd){
                            jnbd[ nbdindex ] = jak;
                            len2nbd[ nbdsize ] = jak;
                            nbdsize++;
                            nbdindex++;
                        }
                    }
                }
            }
        }
        inbd[ i  ] = inbd[ i - 1 ] + nbdsize - len2start;
    }
    
    index    = 0;
    for ( i = 1; i <= m; i++ ) {
        if ( C[ i - 1 ] ){
             for ( j = (int)ia[ i - 1 ]; j < (int)ia[ i ]; j++ ) {
                jaj = (int)ja[ j - 1 ];
                if ( !C[ jaj - 1 ] ) {
                    /*mexPrintf("  %d is a F point nbd of %d\n", jaj, i);*/
                    for ( k = (int)ia [ jaj - 1 ]; k < (int)ia[ jaj ] ; k++ ){
                        jak = (int)ja[ k - 1 ];
                        isinnbd = 0;
                        for ( l = inbd[ i - 1 ]; l < inbd[ i ];  l++ ){
                            if (jnbd[ l - 1 ] == jak){
                                isinnbd = 1;
                                break;
                            }
                        }
                        
                        if (isinnbd) {
                            if ( C [ jak - 1 ] && jak != i){
                                npath[ jak - 1 ]++;
                            }
                        }
                    }                        
                }
            }
            
            for ( j = (int)ia[ i - 1 ]; j < (int)ia[ i ]; j++ ) {
                jaj = (int)ja[ j - 1 ];
                if ( !C[ jaj - 1 ] ) {
                    for ( k = (int)ia [ jaj - 1 ]; k < (int)ia[ jaj ] ; k++ ){
                        jak = (int)ja[ k - 1 ];
                        if ( C [ jak - 1 ] && jak != i && npath[ jak - 1 ] > 0  ){
                            if ( npath[ jak - 1 ] >= path){
                                is2[ index ] = i;
                                js2[ index ] = jak;
                                as2[ index ] = 1;
                                index++;
                            }
                            npath[ jak - 1 ] = 0.0;
                            
                        }
                    }                        
                }
            }
        }        
    }    
    free(npath);
    free(len2nbd);
    *mxGetPr(plhs[3])=(double)index;
    return;
}
コード例 #11
0
ファイル: DespikeOptimise.c プロジェクト: psy2013GitHub/Atom
void icatb_fun(double *xestimate, double *yestimate, double *vTC, double TR, int method)
{
  int nTp, numP, n;
	double *t;
	double err;
  double *x, *y;
	int i,iter,funeval,how;
  double *xbar, *xr, *xe, *xc;
  mxArray *mxv, *mxtmpv;
  double *v, *tmpv, *fv;
  double *rawOrder;

	nTp=sizeof(vTC)/sizeof(double);
  n=sizeof(xestimate)/sizeof(double);
	// init t
  t = malloc(nTp*double);
  for(i=0;i<nTp;++i)
    *(t+i)=i*TR;
  if(method==SPLINEFUN)
    numP=nt/30;
  //start point
  if(method==QUAFUN)
  {
    
  }
  else if(method==SPLINEFUN)
  {
    startpoint;
    srand((unsigned int)time(NULL));
    for(i=0;i<n;++i)
      *(xestimate)=double(rand());
  }

/*############### FMINSEARCH START ###############*/
  n=sizeof(xestimate)/sizeof(double);
  // Set up a simplex near the initial guess.
  mxv=mxCreateDoubleMatrix(n,n+1,mxReal);
  fv=malloc((n+1)*sizeof(double));
  x=malloc(n*sizeof(double));
  v=mxGetPr(mxv);
  for(i=0;i<n+1;++i) //column
    {
      for(j=0;j<n;++j)
        {
          val=*(x+j);
          if(i&&j==i-1) //exlude first column
            {
              if(val)
                val*=(1 + USUAL_DELTA);
              else
                val=ZERO_TERM_DELTA;
            }
            *(v+i*n+j)=val;
            *(x+j)=val;
        }
        y=icatb_quadObj(vTC,t,x);
        free(x);
        *(fv+i)=y;
    }
    // sort v & fv
    mxtmpv=mxDuplicateArray(v);
    tmpv=mxGetPr(mxtmpv);
    rawOrder=malloc((n+1)*sizeof(int));
    indvec(rawOrder, n+1);
    quickSort(fv,rawOrder,0,n);
    for(i=0;i<n+1;++i) //column
      {
        for(j=0;j<n;++j)
          *(v+i*n+j)=*(tmp_v+*(rawOrder+i)*n+j); // change column
      }
    mxDestroyArray(mxtmpv);
    how = INITAL_SIMPLEX;
    
    /*
    % Main algorithm: iterate until 
    % (a) the maximum coordinate difference between the current best point and the 
    % other points in the simplex is less than or equal to TOLX. Specifically,
    % until max(||v2-v1||,||v2-v1||,...,||v(n+1)-v1||) <= TOLX,
    % where ||.|| is the infinity-norm, and v1 holds the 
    % vertex with the current lowest value; AND
    % (b) the corresponding difference in function values is less than or equal
    % to TolFun. (Cannot use OR instead of AND.)
    % The iteration stops if the maximum number of iterations or function evaluations 
    % are exceeded
    */
    xbar=malloc(sizeof(double)*n);
    while(iter<maxIer)
      {
        // max(abs(fv(1)-fv(two2np1)))
        for(i=1;i<n+1;++i)
          if(abs(*fv-*(fv+i))>max(TOLF,10*eps(fv(1))))
            break;
        if(i>=n+1)
          {
            epsv=*v;
            for(j=1;j<n;++j)
              if(epsv<*(v+j))
                epsv=*(v+j);
            for(i=1;i<n+1;++i)
              for(j=0;j<n;++j)
                if(abs(*(v+i*n+j)-*(v+(i-1)*n+j))>max(TOLX,10*eps(fv(1))))
                  break;
          }
        if(i>=n+1)
          break;
        for(i=0;i<n;++i) //0~n-1
          for(j=0;j<n;++j)
              if(!j)
                *(xbar+j)=*(v+i*n+j)/n;
              else
                *(xbar+j)+=*(v+i*n+j)/n;
      
        // xr = (1 + RHO)*xbar - RHO*v(:,end);
        xr=malloc(sizeof(xbar));
        for(j=0;j<n;++j)
          *(xr+j)=*(xbar+j)*(1+RHO) - *(v+n*n+j)*RHO;
        fxr=icatb_quadObj(vTC, t, xr);
        if(fxr<*(fv))
         {
          xe=malloc(sizeof(xbar));
          for(j=0;j<n;++j)
              *(xe+j)=*(xbar+j)*(1+RHO*CHI) - *(v+n*n+j)*RHO*CHI;
          fxe=icatb_quadObj(vTC, t, xe);
          if(fxe<fxr)
           {
            for(j=0;j<n;++j)
              *(v+n*n+j)=*(xe+j);
            *(fv+n)=fxe;
            how=EXPAND; //how='expand'
           }
          else
           {
            for(j=0;j<n;++j)
              *(v+n*n+j)=*(xr+j);
            *(fv+n)=fxr;
            how=REFLECT; //how='reflect'
           }
          free(xe);
         }
        else
         {
          if(fxr<*(fv+n-1)) //fxr<fv(:,n)
           {
            for(j=0;j<n;++j)
              *(v+n*n+j)=*(xr+j)
            *(fv+n)=fxr;
            how=REFLECT; //how='reflect'
           }
          else
           {
            xc=malloc(sizeof(xbar));
            if(fxr<*(fv+n)) //if(fxr<fv(:,end));
            {
              for(j=0;j<n;++j)
                *(xc+j)=*(xbar+j)*(1+PSI*RHO) - *(v+n*n+j)*PSI*RHO;
              fxc=icatb_quadObj(vTC, t, xc);
              if(fxc<=fxr)
              {
                for(j=0;j<n;++j)
                  *(v+n*n+j)=*(xc+j);
                *(fv+n)=fxc;
                how=CONTRCT_OUTSIDE; //how='contract outside'
              }
              else
                how=SHRINK;
            }
            else
            {
              for(j=0;j<n;++j)
                *(xc+j)=*(xbar+j)*(1-PSI) - *(v+n*n+j)*PSI; //xcc = (1-PSI)*xbar + PSI*v(:,end);
              fxc=icatb_quadObj(vTC, t, xc);
              if(fxc<*(fv+n))
              {
                for(j=0;j<n;++j)
                  *(v+n*n+j)=*(xc+j);
                *(fv+n)=fxc;
                how=CONTRACT_INSIDE; //how='contract inside'                
              }
              else
                how=SHRINK; //how='shrink';
            }
            if(how==SHRINK)
              for(i=1;i<n+1;++i)
                {
                  for(j=0;j<n;++j)
                    {
                      *(v+i*n+j)=*(v+j) + (*(v+i*n+j) - *(v+j))*SIGMA; 
                      *(xc+j)=*(v+i*n+j);
                    }
                  *(fv+i)=icatb_quadObj(vTC, t, xc);
                }
            }
            free(xc);
           }
        indvec(rawOrder, n+1);
        quickSort(fv,rawOrder,0,n);
        mxtmpv=mxDuplicateArray(v);
        for(i=0;i<n+1;++i) //column
          {
           for(j=0;j<n;++j)
           *(v+i*n+j)=*(tmp_v + *(rawOrder+i)*n + j); // change column
          }
       }
    for(j=0;j<n;++j)
      *(xestimate+j)=*(v+j);
    *yestimate=*fv;
    //
    free(rawOrder);
    mxDestroyArray(mxv);
    mxDestroyArray(mxtmpv);
    free(fv);
    free(xbar);

/*############### FMINSEARCH  END  ###############*/

  free(t);
}
コード例 #12
0
ファイル: m1qn3mex.c プロジェクト: BackupTheBerlios/gtde-svn
// Function definitions. 
// -----------------------------------------------------------------
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{
    //Input Args
    double *x0;          

    //Outputs Args
    double *x, *fval, *exitflag, *iter, *feval;
    
    //Internal Vars
    size_t ndec;  
    int printLevel = 0;
    
    //M1QN3 Vars
    int m = 5, n, indic, ndz;
    int uiparm[2] = {1,0};  //user integer array [citer, printLevel]
    double *g, dxmin = 1e-8, df1, epsg = 1e-6, *dz;
    char *normtype = "dfn";
    int impres = 4, io = 18, omode = 0, reverse = 0;
    int imode[3] = {0,0,0}; //DIS, cold start, no SIMUL with indic = 1
    int iz[5];
    float *rzs = NULL; double *dzs = NULL; //dummy args
    //Defaults
    int maxfev = 1500;
    int maxiter = 1000;
    maxtime = 1000;
    iterF.enabled = false;

    if (nrhs < 1) {
        if(nlhs < 1)
            mexPrintf("\nThis is M1QN3 v%s MEX Interface\n",M1QN3_VERSION);
        else
            plhs[0] = mxCreateString(M1QN3_VERSION);
            
        return;
    }

    //Check user inputs
    checkInputs(prhs,nrhs);

    //Get Sizes
    ndec = mxGetNumberOfElements(pX0);
    //Get Objective Function Handle
    if (mxIsChar(pFUN)) {
        CHECK(mxGetString(pFUN, fun.f, FLEN) == 0,"error reading objective name string");
        fun.nrhs = 1;
        fun.xrhs = 0;
    } else {
        fun.prhs[0] = (mxArray*)pFUN;
        strcpy(fun.f, "feval");
        fun.nrhs = 2;
        fun.xrhs = 1;
    }
    fun.prhs[fun.xrhs] = mxCreateDoubleMatrix(ndec, 1, mxREAL); //x0
    //Get Gradient Function Handle 
    if (mxIsChar(pGRAD)) {
        CHECK(mxGetString(pGRAD, fun.g, FLEN) == 0,"error reading gradient name string");
        fun.nrhs_g = 1;
        fun.xrhs_g = 0;
    } else {
        fun.prhs_g[0] = (mxArray*)pGRAD;
        strcpy(fun.g, "feval");
        fun.nrhs_g = 2;
        fun.xrhs_g = 1;
    }   
    fun.prhs_g[fun.xrhs_g] = mxCreateDoubleMatrix(ndec, 1, mxREAL); //x0   

    //Get x0
    x0 = mxGetPr(pX0);
    
    //Get Options if specified
    if(nrhs > eOPTS) {
        if(mxGetField(pOPTS,0,"display"))
            printLevel = (int)*mxGetPr(mxGetField(pOPTS,0,"display"));
        if(mxGetField(pOPTS,0,"maxfeval"))
            maxfev = (int)*mxGetPr(mxGetField(pOPTS,0,"maxfeval"));
        if(mxGetField(pOPTS,0,"maxiter"))
            maxiter = (int)*mxGetPr(mxGetField(pOPTS,0,"maxiter"));
        if(mxGetField(pOPTS,0,"maxtime"))
            maxtime = *mxGetPr(mxGetField(pOPTS,0,"maxtime"));
        if(mxGetField(pOPTS,0,"tolafun"))
            epsg = *mxGetPr(mxGetField(pOPTS,0,"tolafun")); //not function tolerance (gradient)
        if(mxGetField(pOPTS,0,"nupdates"))
            m = (int)*mxGetPr(mxGetField(pOPTS,0,"nupdates")); //number of l-bfgs updates
        if(mxGetField(pOPTS,0,"iterfun") && !mxIsEmpty(mxGetField(pOPTS,0,"iterfun")))
        {
            iterF.prhs[0] = (mxArray*)mxGetField(pOPTS,0,"iterfun");
            strcpy(iterF.f, "feval");
            iterF.enabled = true;  
            iterF.prhs[1] = mxCreateNumericMatrix(1,1,mxINT32_CLASS,mxREAL);
            iterF.prhs[2] = mxCreateDoubleMatrix(1,1,mxREAL);
            iterF.prhs[3] = mxCreateDoubleMatrix(ndec,1,mxREAL);
        }
    }       
    
    //Create Outputs
    plhs[0] = mxCreateDoubleMatrix(ndec,1, mxREAL);
    plhs[1] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[2] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[3] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[4] = mxCreateDoubleMatrix(1,1, mxREAL);
    x = mxGetPr(plhs[0]); 
    fval = mxGetPr(plhs[1]); 
    exitflag = mxGetPr(plhs[2]);    
    iter = mxGetPr(plhs[3]);
    feval = mxGetPr(plhs[4]);
    
    //Copy initial guess to x
    memcpy(x,x0,ndec*sizeof(double));
    
    //Print Header
    if(printLevel) {
        mexPrintf("\n------------------------------------------------------------------\n");
        mexPrintf(" This is M1QN3 v%s\n",M1QN3_VERSION);  
        mexPrintf(" Authors: Jean Charles Gilbert, Claude Lemarechal, INRIA\n MEX Interface J. Currie 2012\n\n");
        mexPrintf(" Problem Properties:\n");
        mexPrintf(" # Decision Variables:     %4d\n",ndec);

        mexPrintf("------------------------------------------------------------------\n");
    }
    
    //Assign Arguments
    n = (int)ndec;
    indic = 4;
    g = (double*)mxCalloc(n,sizeof(double)); //allocate memory for gradient
    ndz = 4*n + m*(2*n + 1);
    dz = (double*)mxCalloc(ndz,sizeof(double));
    
    //Start timer
    start = clock();
    
    //Initialization Call
    SIMUL(&indic, &n, x, fval, g, uiparm, NULL, NULL);    
    //Set df1 (initial estiamte of f reduction)
    df1 = *fval;
    
    //MEX Options
    uiparm[0] = 1;
    uiparm[1] = printLevel;
    
//     FILE* myFile = fopen("myFile.txt","w");
//     fprintf(myFile,"Hello world!\n");
//     fclose(myFile);
    
    //Call Algorithm
    M1QN3(SIMUL,EUCLID,CTONBE,CTCABE,&n,x,fval,g,&dxmin,&df1,&epsg,normtype,
          &impres,&io,imode,&omode,&maxiter,&maxfev,iz,dz,&ndz,&reverse,&indic,
          uiparm,rzs,dzs);

    //Save Status & Iterations
    *exitflag = (double)omode;
    *iter = maxiter;
    *feval = maxfev;
    
    //Check if maxtime exceeded
    if(((double)(end-start))/CLOCKS_PER_SEC > maxtime)
        *exitflag = 8;
    
    //Print Header
    if(printLevel){            
        //Termination Detected
        switch((int)*exitflag)
        {
            //Success
            case 1:
                mexPrintf("\n *** SUCCESSFUL TERMINATION ***\n *** gradient convergence |gk|/|g1| < epsg ***\n"); break;
            //Error
            case 5:
                mexPrintf("\n *** MAXIMUM FUNCTION EVALUATIONS REACHED ***\n"); break;
            case 4:
                mexPrintf("\n *** MAXIMUM ITERATIONS REACHED ***\n"); break;                       
            case 8:
                mexPrintf("\n *** MAXIMUM TIME REACHED ***\n"); break;  
            case 2:
                mexPrintf("\n *** ERROR: one of the input arguments is not well initialized ***\n"); break;
            case 3:
                mexPrintf("\n *** ERROR: the line-search is blocked on tmax = 10^20 ***\n"); break;    
            case 6:
                mexPrintf("\n *** ERROR: stop dxmin during the line-search ***\n"); break;       
            case 7:
                mexPrintf("\n *** ERROR: either (g,d) is nonnegative or (y,s) is nonpositive ***\n"); break;
            //Early Exit
            case 0:
                mexPrintf("\n *** TERMINATION: USER EXITED ***\n"); break;
            //Other Error
            default:
                mexPrintf("\n *** ERROR: internal error code %d ***\n",omode); break;
        }
        
        if(*exitflag==1)
            mexPrintf("\n Final fval: %12.5g\n In %3.0f iterations\n",*fval,*iter);

        mexPrintf("------------------------------------------------------------------\n\n");
    }
    
    //Free Memory
    mxFree(g);
    mxFree(dz);
}
コード例 #13
0
ファイル: m1qn3mex.c プロジェクト: BackupTheBerlios/gtde-svn
//MATLAB Callback
static void SIMUL(int *indic, int *n, double *x, double *f, double *g, int *izs, float *rzs, double *dzs)
{
    int stat;
    double *grad;   
    bool stop = false;
    double evaltime;

    //Get Execution Time
    end = clock();
    evaltime = ((double)(end-start))/CLOCKS_PER_SEC;
    
    //Check for Ctrl-C
    if (utIsInterruptPending()) {
        utSetInterruptPending(false); /* clear Ctrl-C status */
        mexPrintf("\nCtrl-C Detected. Exiting M1QN3...\n\n");
        *indic = 0; //terminate
        return;
    }
    
    //Check for maxtime expiry    
    if(evaltime > maxtime)
    {
        mexPrintf("\nMaximum Solver Time Exceeded. Exiting M1QN3...\n\n");
        *indic = 0; //terminate
        return;
    }
    
    //Only compute f and g if requested
    if(*indic == 4)
    {    
        fun.plhs[0] = NULL;
        memcpy(mxGetPr(fun.prhs[fun.xrhs]), x, *n * sizeof(double));

        stat = mexCallMATLAB(1, fun.plhs, fun.nrhs, fun.prhs, fun.f);
        if(stat)
          mexErrMsgTxt("Error calling Objective Function!");

        //Get Objective
        *f = *mxGetPr(fun.plhs[0]);
        // Clean up Ptr
        mxDestroyArray(fun.plhs[0]);
        
        //Check for inf, nan
        if(mxIsInf(*f) || mxIsNaN(*f))
            *indic = -1; //indicate smaller step size

        //Get Gradient
        fun.plhs[0] = NULL;
        memcpy(mxGetPr(fun.prhs_g[fun.xrhs_g]), x, *n * sizeof(double));

        stat = mexCallMATLAB(1, fun.plhs, fun.nrhs_g, fun.prhs_g, fun.g);
        if(stat)
          mexErrMsgTxt("Error calling Gradient Function!");

        //Get Gradient
        grad = mxGetPr(fun.plhs[0]);
        //Assign Gradient
        memcpy(g,grad,*n*sizeof(double));

        // Clean up Ptr
        mxDestroyArray(fun.plhs[0]);

        //Iteration Printing
        if(izs[1] > 1) {               
            if(izs[0] == 1 || !(izs[0]%10))
                mexPrintf(" feval       time           fval\n");

            mexPrintf("%5d       %5.2f    %12.5g\n",izs[0],evaltime,*f);
            mexEvalString("drawnow;"); //flush draw buffer
        }

        //Iteration Callback
        if(iterF.enabled)
        {
            iterF.plhs[0] = NULL;
            memcpy(mxGetData(iterF.prhs[1]), izs, sizeof(int));
            memcpy(mxGetPr(iterF.prhs[2]), f, sizeof(double));
            memcpy(mxGetPr(iterF.prhs[3]), x, *n * sizeof(double));
            stat = mexCallMATLAB(1, iterF.plhs, 4, iterF.prhs, iterF.f);
            if(stat)
                mexErrMsgTxt("Error calling Callback Function!");

            //Collect return argument
            stop = *(bool*)mxGetData(iterF.plhs[0]);
            // Clean up Ptr
            mxDestroyArray(iterF.plhs[0]);

            if(stop)
                *indic = 0; //force exit
        }
    
        //Increment feval counter
        izs[0]++;
    }
}
コード例 #14
0
ファイル: cmex.c プロジェクト: AMFIRNAS/wso2-gridlabd
static mxArray *get_object_data(OBJECT *obj)
{
	mxArray *plhs[1];

	/* set the standard info */
#define ERROR "(error)"
#define NONE "(none)"
	char *fnames[1024] = {"id","class","parent","rank","clock","latitude","longitude","in_svc","out_svc","flags",NULL}; // };
	int nFields = 0;
	int nData = 0;
	char value[1024];
	PROPERTY *prop;
	mxArray *pId = mxCreateString(convert_from_object(value,sizeof(value),&obj,NULL)?value:ERROR);
	mxArray *pClass = mxCreateString(obj->oclass->name);
	mxArray *pParent = mxCreateString(obj->parent!=NULL&&convert_from_object(value,sizeof(value),&(obj->parent),NULL)?value:NONE);
	mxArray *pRank = mxCreateNumericMatrix(1,1,mxUINT32_CLASS,mxREAL);
	mxArray *pClock = mxCreateString(convert_from_timestamp(obj->clock,value,sizeof(value))?value:ERROR);
	mxArray *pLatitude = mxCreateString(convert_from_latitude(obj->latitude,value,sizeof(value))?value:NONE);
	mxArray *pLongitude = mxCreateString(convert_from_longitude(obj->longitude,value,sizeof(value))?value:NONE);
	mxArray *pInSvc = mxCreateString(convert_from_timestamp(obj->in_svc,value,sizeof(value))?value:ERROR);
	mxArray *pOutSvc = mxCreateString(convert_from_timestamp(obj->out_svc,value,sizeof(value))?value:ERROR);
	mxArray *pFlags = mxCreateString(convert_from_set(value,sizeof(value),(void*)&obj->flags,object_flag_property())?value:ERROR);

	*(OBJECTRANK*)mxGetPr(pRank) = obj->rank;

	/* count the number of header items */
	while (fnames[nFields]!=NULL) nFields++;

	/* count the number of object properties and assign the field names */
	for (prop=class_get_first_property(obj->oclass);  prop!=NULL; prop=class_get_next_property(prop))
		/** @todo don't damage the original fieldname when making it safe for Matlab */
		fnames[nFields+nData++] = make_fieldname(prop->name);

	/* construct the return value */
	plhs[0] = mxCreateStructMatrix(1,1,nFields+nData,fnames);

	/* construct the header fields */
	mxSetFieldByNumber(plhs[0],0,0,pId);
	mxSetFieldByNumber(plhs[0],0,1,pClass);
	mxSetFieldByNumber(plhs[0],0,2,pParent);
	mxSetFieldByNumber(plhs[0],0,3,pRank);
	mxSetFieldByNumber(plhs[0],0,4,pClock);
	mxSetFieldByNumber(plhs[0],0,5,pLatitude);
	mxSetFieldByNumber(plhs[0],0,6,pLongitude);
	mxSetFieldByNumber(plhs[0],0,7,pInSvc);
	mxSetFieldByNumber(plhs[0],0,8,pOutSvc);
	mxSetFieldByNumber(plhs[0],0,9,pFlags);

	/* construct the data fields */
	for (prop=class_get_first_property(obj->oclass);  prop!=NULL; nFields++,prop=class_get_next_property(prop))
	{
		mxArray *pValue;
		if (prop->ptype==PT_double)
		{
			pValue = mxCreateDoubleMatrix(1,1,mxREAL);
			*(double*)mxGetPr(pValue) = *object_get_double(obj,prop);
		}
		else if (prop->ptype==PT_int32)
		{
			pValue = mxCreateDoubleMatrix(1,1,mxREAL);
			*(double*)mxGetPr(pValue) = (double)*object_get_int32(obj,prop);
		}
		else if (prop->ptype==PT_complex)
		{
			complex *pData = object_get_complex(obj,prop);
			pValue = mxCreateDoubleMatrix(1,1,mxCOMPLEX);
			*(double*)mxGetPr(pValue) = pData->r;
			*(double*)mxGetPi(pValue) = pData->i;
		}
		else 
		{
			pValue = mxCreateString(object_get_value_by_name(obj,prop->name,value,sizeof(value))?value:ERROR);
		}
		mxSetFieldByNumber(plhs[0],0,nFields,pValue);
	}
	return plhs[0];
}
コード例 #15
0
void mexFunction ( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
	Dbptr	db;
	int	single_row;
	long	nrows;
	int	code = 0;
	int	rc = 0;
	char	*expression;
	char	*codestr;
	Expression *expr;
	Dbvalue	exresult;
	double	*pr;

	if( nrhs != 2 && nrhs != 3 )
	{
		antelope_mexUsageMsgTxt ( USAGE );
		return;
	}
        else if( ! get_dbptr( prhs[0], &db ) )
        {
                antelope_mexUsageMsgTxt ( USAGE );
		return;
        }
        else if( ! mtlb_get_string( prhs[1], &expression ) )
        {
                antelope_mexUsageMsgTxt ( USAGE );
		return;
        }
        else if( nrhs == 3 && ! mtlb_get_string( prhs[2], &codestr ) )
        {
		mxFree( expression );
                antelope_mexUsageMsgTxt ( USAGE );
		return;
        }
	else if( nrhs == 3 )
	{
		code = xlatname( codestr, Dbxlat, NDbxlat );
		mxFree( codestr );
	}

	if( dbex_compile( db, expression, &expr, code ) < 0 )
	{
		antelope_mex_clear_register( 1 );
		mxFree( expression );
		mexErrMsgTxt( "dbeval: expression failed to compile\n" );
	}
	else
	{
		antelope_mex_clear_register( 1 );
		mxFree( expression );
	}

	rc = dbquery( db, dbRECORD_COUNT, &nrows );
	antelope_mex_clear_register( 1 );
	if( rc == dbINVALID ) 
	{
		mexErrMsgTxt( "dbgetv: query for number of records failed" );
	}

	if( db.record == dbALL ) {
		if( nrows == 1 ) {
			single_row = 1;
			db.record = 0;
		} else {
			single_row = 0;
		}
	} else {
		single_row = 1;
	}

	if( single_row ) 
	{
		rc = dbex_eval ( db, expr, 1, &exresult ) ;
		antelope_mex_clear_register( 1 );

		if( rc >= 0 )
		{
		   switch( expr->type )
		   {
			case dbBOOLEAN:
			case dbINTEGER:
			case dbYEARDAY:
				plhs[0] = CreateDouble( (double)  exresult.i );
				if( plhs[0] == NULL )
				{
					dbex_free( expr );
					mexErrMsgTxt( 
				   	"dbeval: failed to create return value" );
				}
				break;
			case dbREAL:
			case dbTIME:
				plhs[0] = CreateDouble( exresult.d );
				if( plhs[0] == NULL )
				{
					dbex_free( expr );
					mexErrMsgTxt( 
				   	"dbeval: failed to create return value" );
				}
				break;
			case dbSTRING:
				plhs[0] = mxCreateString( exresult.t );
				free( exresult.t );
				break;
			default:
				dbex_free( expr );
				mexErrMsgTxt( "Unknown type in dbeval\n" );
				break;
		   }
		   dbex_free( expr );
		}
		else
		{
			dbex_free( expr );
			mexErrMsgTxt( "dbeval: eval failed\n" );
		}
	} else {

		db.record = 0;

		rc = dbex_eval ( db, expr, 1, &exresult ) ;
		antelope_mex_clear_register( 1 );

		if( rc >= 0 )
		{
		   switch( expr->type )
		   {
			case dbBOOLEAN:
			case dbINTEGER:
			case dbYEARDAY:
				plhs[0] = mxCreateDoubleMatrix( nrows, 1, mxREAL );
				if( plhs[0] == NULL )
				{
					dbex_free( expr );
					mexErrMsgTxt( 
				   	"dbeval: failed to create return value" );
				}

				pr = mxGetPr( plhs[0] );
				pr[db.record] = (double) exresult.i;

				for( db.record = 1; db.record < nrows; db.record++ )
				{
					if( dbex_eval ( db, expr, 1, &exresult ) < 0 ) 
					{
						antelope_mex_clear_register( 1 );
						dbex_free( expr );
						mxDestroyArray( plhs[0] );
						mexErrMsgTxt( "dbeval: eval failed\n" );
					} else {
						pr[db.record] = (double) exresult.i;
					}
				}

				break;
			case dbREAL:
			case dbTIME:
				plhs[0] = mxCreateDoubleMatrix( nrows, 1, mxREAL );
				if( plhs[0] == NULL )
				{
					dbex_free( expr );
					mexErrMsgTxt( 
				   	"dbeval: failed to create return value" );
				}

				pr = mxGetPr( plhs[0] );
				pr[db.record] = exresult.d;

				for( db.record = 1; db.record < nrows; db.record++ )
				{
					if( dbex_eval ( db, expr, 1, &exresult ) < 0 ) 
					{
						antelope_mex_clear_register( 1 );
						dbex_free( expr );
						mxDestroyArray( plhs[0] );
						mexErrMsgTxt( "dbeval: eval failed\n" );
					} else {
						pr[db.record] = (double) exresult.d;
					}
				}

				break;
			case dbSTRING:
				plhs[0] = mxCreateCellMatrix( nrows, 1 );
				if( plhs[0] == NULL )
				{
					dbex_free( expr );
					mexErrMsgTxt( 
				   	"dbeval: failed to create return value" );
				}

				mxSetCell( plhs[0], db.record, mxCreateString( exresult.t ) );
				free( exresult.t );

				for( db.record = 1; db.record < nrows; db.record++ )
				{
					if( dbex_eval ( db, expr, 1, &exresult ) < 0 ) 
					{
						antelope_mex_clear_register( 1 );
						dbex_free( expr );
						mxDestroyArray( plhs[0] );
						mexErrMsgTxt( "dbeval: eval failed\n" );
					} else {
						mxSetCell( plhs[0], db.record, mxCreateString( exresult.t ) );
						free( exresult.t );
					}
				}

				break;
			default:
				dbex_free( expr );
				mexErrMsgTxt( "Unknown type in dbeval\n" );
				break;
		   }
		   dbex_free( expr );
		}
		else
		{
			dbex_free( expr );
			mexErrMsgTxt( "dbeval: eval failed\n" );
		}
	}
}
コード例 #16
0
ファイル: Model_01_sfun.c プロジェクト: phillip-s/Model_01
unsigned int sf_Model_01_process_check_sum_call( int nlhs, mxArray * plhs[], int
  nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2395467678U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2655813948U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1733208674U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3001864846U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1467923453U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2112315684U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(892916413U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1268429609U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 1:
        {
          extern void sf_c1_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c1_Model_01_get_check_sum(plhs);
          break;
        }

       case 2:
        {
          extern void sf_c2_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c2_Model_01_get_check_sum(plhs);
          break;
        }

       case 3:
        {
          extern void sf_c3_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c3_Model_01_get_check_sum(plhs);
          break;
        }

       case 4:
        {
          extern void sf_c4_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c4_Model_01_get_check_sum(plhs);
          break;
        }

       case 5:
        {
          extern void sf_c5_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c5_Model_01_get_check_sum(plhs);
          break;
        }

       case 6:
        {
          extern void sf_c6_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c6_Model_01_get_check_sum(plhs);
          break;
        }

       case 7:
        {
          extern void sf_c7_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c7_Model_01_get_check_sum(plhs);
          break;
        }

       case 8:
        {
          extern void sf_c8_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c8_Model_01_get_check_sum(plhs);
          break;
        }

       case 9:
        {
          extern void sf_c9_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c9_Model_01_get_check_sum(plhs);
          break;
        }

       case 10:
        {
          extern void sf_c10_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c10_Model_01_get_check_sum(plhs);
          break;
        }

       case 11:
        {
          extern void sf_c11_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c11_Model_01_get_check_sum(plhs);
          break;
        }

       case 12:
        {
          extern void sf_c12_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c12_Model_01_get_check_sum(plhs);
          break;
        }

       case 13:
        {
          extern void sf_c13_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c13_Model_01_get_check_sum(plhs);
          break;
        }

       case 14:
        {
          extern void sf_c14_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c14_Model_01_get_check_sum(plhs);
          break;
        }

       case 15:
        {
          extern void sf_c15_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c15_Model_01_get_check_sum(plhs);
          break;
        }

       case 16:
        {
          extern void sf_c16_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c16_Model_01_get_check_sum(plhs);
          break;
        }

       case 17:
        {
          extern void sf_c17_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c17_Model_01_get_check_sum(plhs);
          break;
        }

       case 18:
        {
          extern void sf_c18_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c18_Model_01_get_check_sum(plhs);
          break;
        }

       case 19:
        {
          extern void sf_c19_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c19_Model_01_get_check_sum(plhs);
          break;
        }

       case 20:
        {
          extern void sf_c20_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c20_Model_01_get_check_sum(plhs);
          break;
        }

       case 21:
        {
          extern void sf_c21_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c21_Model_01_get_check_sum(plhs);
          break;
        }

       case 22:
        {
          extern void sf_c22_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c22_Model_01_get_check_sum(plhs);
          break;
        }

       case 23:
        {
          extern void sf_c23_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c23_Model_01_get_check_sum(plhs);
          break;
        }

       case 24:
        {
          extern void sf_c24_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c24_Model_01_get_check_sum(plhs);
          break;
        }

       case 25:
        {
          extern void sf_c25_Model_01_get_check_sum(mxArray *plhs[]);
          sf_c25_Model_01_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3031367619U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(4001028638U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3978939492U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(838979348U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1837104763U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1287062488U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3131336106U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3738581954U);
  }

  return 1;

#else

  return 0;

#endif

}
コード例 #17
0
ファイル: svmpredict.c プロジェクト: DiNAi/OrdinalFramework
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 ||
		   nr_class == 1) // if only one class in training data, decision values are still returned.
			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
		{
			if(svm_type == ONE_CLASS ||
			   svm_type == EPSILON_SVR ||
			   svm_type == NU_SVR)
			{
				double res;
				predict_label = 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);
				predict_label = svm_predict_values(model, x, dec_values);
				if(nr_class == 1) 
					ptr_dec_values[instance_index] = 1;
				else
					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);
			}
			ptr_predict_label[instance_index] = predict_label;
		}

		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);
}
コード例 #18
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  int i, j;
  mxArray *xm, *cell, *xm_cell;
  double *src;
  double *dest;
  double *dest_cell;
  int valid_vars;
  int steps;
  int this_var_errors;
  int warned_diags;
  int prepare_for_c = 0;
  int extra_solves;
  const char *status_names[] = {"optval", "gap", "steps", "converged"};
  mwSize dims1x1of1[1] = {1};
  mwSize dims[1];
  const char *var_names[] = {"u_0", "u_1", "u_2", "u_3", "u_4", "u_5", "u_6", "u_7", "u_8", "u_9", "x_1", "x_2", "x_3", "x_4", "x_5", "x_6", "x_7", "x_8", "x_9", "x_10", "u", "x"};
  const int num_var_names = 22;
  /* Avoid compiler warnings of unused variables by using a dummy assignment. */
  warned_diags = j = 0;
  extra_solves = 0;
  set_defaults();
  /* Check we got the right number of arguments. */
  if (nrhs == 0)
    mexErrMsgTxt("Not enough arguments: You need to specify at least the parameters.\n");
  if (nrhs > 1) {
    /* Assume that the second argument is the settings. */
    if (mxGetField(prhs[1], 0, "eps") != NULL)
      settings.eps = *mxGetPr(mxGetField(prhs[1], 0, "eps"));
    if (mxGetField(prhs[1], 0, "max_iters") != NULL)
      settings.max_iters = *mxGetPr(mxGetField(prhs[1], 0, "max_iters"));
    if (mxGetField(prhs[1], 0, "refine_steps") != NULL)
      settings.refine_steps = *mxGetPr(mxGetField(prhs[1], 0, "refine_steps"));
    if (mxGetField(prhs[1], 0, "verbose") != NULL)
      settings.verbose = *mxGetPr(mxGetField(prhs[1], 0, "verbose"));
    if (mxGetField(prhs[1], 0, "better_start") != NULL)
      settings.better_start = *mxGetPr(mxGetField(prhs[1], 0, "better_start"));
    if (mxGetField(prhs[1], 0, "verbose_refinement") != NULL)
      settings.verbose_refinement = *mxGetPr(mxGetField(prhs[1], 0,
            "verbose_refinement"));
    if (mxGetField(prhs[1], 0, "debug") != NULL)
      settings.debug = *mxGetPr(mxGetField(prhs[1], 0, "debug"));
    if (mxGetField(prhs[1], 0, "kkt_reg") != NULL)
      settings.kkt_reg = *mxGetPr(mxGetField(prhs[1], 0, "kkt_reg"));
    if (mxGetField(prhs[1], 0, "s_init") != NULL)
      settings.s_init = *mxGetPr(mxGetField(prhs[1], 0, "s_init"));
    if (mxGetField(prhs[1], 0, "z_init") != NULL)
      settings.z_init = *mxGetPr(mxGetField(prhs[1], 0, "z_init"));
    if (mxGetField(prhs[1], 0, "resid_tol") != NULL)
      settings.resid_tol = *mxGetPr(mxGetField(prhs[1], 0, "resid_tol"));
    if (mxGetField(prhs[1], 0, "extra_solves") != NULL)
      extra_solves = *mxGetPr(mxGetField(prhs[1], 0, "extra_solves"));
    else
      extra_solves = 0;
    if (mxGetField(prhs[1], 0, "prepare_for_c") != NULL)
      prepare_for_c = *mxGetPr(mxGetField(prhs[1], 0, "prepare_for_c"));
  }
  valid_vars = 0;
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "A");
  if (xm == NULL) {
    printf("could not find params.A.\n");
  } else {
    if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 3))) {
      printf("A must be size (3,3), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter A must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter A must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter A must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.A;
      src = mxGetPr(xm);
      for (i = 0; i < 9; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "B");
  if (xm == NULL) {
    printf("could not find params.B.\n");
  } else {
    if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 1))) {
      printf("B must be size (3,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter B must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter B must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter B must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.B;
      src = mxGetPr(xm);
      for (i = 0; i < 3; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "Ff");
  if (xm == NULL) {
    printf("could not find params.Ff.\n");
  } else {
    if (!((mxGetM(xm) == 2) && (mxGetN(xm) == 3))) {
      printf("Ff must be size (2,3), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter Ff must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter Ff must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter Ff must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.Ff;
      src = mxGetPr(xm);
      for (i = 0; i < 6; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "Fu");
  if (xm == NULL) {
    printf("could not find params.Fu.\n");
  } else {
    if (!((mxGetM(xm) == 4) && (mxGetN(xm) == 1))) {
      printf("Fu must be size (4,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter Fu must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter Fu must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter Fu must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.Fu;
      src = mxGetPr(xm);
      for (i = 0; i < 4; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "Fus");
  if (xm == NULL) {
    printf("could not find params.Fus.\n");
  } else {
    if (!((mxGetM(xm) == 2) && (mxGetN(xm) == 1))) {
      printf("Fus must be size (2,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter Fus must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter Fus must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter Fus must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.Fus;
      src = mxGetPr(xm);
      for (i = 0; i < 2; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "Fx");
  if (xm == NULL) {
    printf("could not find params.Fx.\n");
  } else {
    if (!((mxGetM(xm) == 4) && (mxGetN(xm) == 3))) {
      printf("Fx must be size (4,3), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter Fx must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter Fx must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter Fx must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.Fx;
      src = mxGetPr(xm);
      for (i = 0; i < 12; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "Fxs");
  if (xm == NULL) {
    printf("could not find params.Fxs.\n");
  } else {
    if (!((mxGetM(xm) == 2) && (mxGetN(xm) == 3))) {
      printf("Fxs must be size (2,3), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter Fxs must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter Fxs must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter Fxs must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.Fxs;
      src = mxGetPr(xm);
      for (i = 0; i < 6; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "Q");
  if (xm == NULL) {
    printf("could not find params.Q.\n");
  } else {
    if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 3))) {
      printf("Q must be size (3,3), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter Q must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter Q must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter Q must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.Q;
      src = mxGetPr(xm);
      for (i = 0; i < 9; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "Q_final");
  if (xm == NULL) {
    printf("could not find params.Q_final.\n");
  } else {
    if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 3))) {
      printf("Q_final must be size (3,3), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter Q_final must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter Q_final must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter Q_final must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.Q_final;
      src = mxGetPr(xm);
      for (i = 0; i < 9; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "R");
  if (xm == NULL) {
    printf("could not find params.R.\n");
  } else {
    if (!((mxGetM(xm) == 1) && (mxGetN(xm) == 1))) {
      printf("R must be size (1,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter R must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter R must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter R must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.R;
      src = mxGetPr(xm);
      for (i = 0; i < 1; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "d");
  if (xm == NULL) {
    printf("could not find params.d.\n");
  } else {
    if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 1))) {
      printf("d must be size (3,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter d must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter d must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter d must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.d;
      src = mxGetPr(xm);
      for (i = 0; i < 3; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "f");
  if (xm == NULL) {
    printf("could not find params.f.\n");
  } else {
    if (!((mxGetM(xm) == 4) && (mxGetN(xm) == 1))) {
      printf("f must be size (4,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter f must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter f must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter f must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.f;
      src = mxGetPr(xm);
      for (i = 0; i < 4; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "ff");
  if (xm == NULL) {
    printf("could not find params.ff.\n");
  } else {
    if (!((mxGetM(xm) == 2) && (mxGetN(xm) == 1))) {
      printf("ff must be size (2,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter ff must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter ff must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter ff must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.ff;
      src = mxGetPr(xm);
      for (i = 0; i < 2; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "fs");
  if (xm == NULL) {
    printf("could not find params.fs.\n");
  } else {
    if (!((mxGetM(xm) == 2) && (mxGetN(xm) == 1))) {
      printf("fs must be size (2,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter fs must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter fs must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter fs must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.fs;
      src = mxGetPr(xm);
      for (i = 0; i < 2; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "x_0");
  if (xm == NULL) {
    printf("could not find params.x_0.\n");
  } else {
    if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 1))) {
      printf("x_0 must be size (3,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter x_0 must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter x_0 must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter x_0 must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.x_0;
      src = mxGetPr(xm);
      for (i = 0; i < 3; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  this_var_errors = 0;
  xm = mxGetField(prhs[0], 0, "xt");
  if (xm == NULL) {
    printf("could not find params.xt.\n");
  } else {
    if (!((mxGetM(xm) == 3) && (mxGetN(xm) == 1))) {
      printf("xt must be size (3,1), not (%d,%d).\n", mxGetM(xm), mxGetN(xm));
      this_var_errors++;
    }
    if (mxIsComplex(xm)) {
      printf("parameter xt must be real.\n");
      this_var_errors++;
    }
    if (!mxIsClass(xm, "double")) {
      printf("parameter xt must be a full matrix of doubles.\n");
      this_var_errors++;
    }
    if (mxIsSparse(xm)) {
      printf("parameter xt must be a full matrix.\n");
      this_var_errors++;
    }
    if (this_var_errors == 0) {
      dest = params.xt;
      src = mxGetPr(xm);
      for (i = 0; i < 3; i++)
        *dest++ = *src++;
      valid_vars++;
    }
  }
  if (valid_vars != 16) {
    printf("Error: %d parameters are invalid.\n", 16 - valid_vars);
    mexErrMsgTxt("invalid parameters found.");
  }
  if (prepare_for_c) {
    printf("settings.prepare_for_c == 1. thus, outputting for C.\n");
    for (i = 0; i < 3; i++)
      printf("  params.x_0[%d] = %.6g;\n", i, params.x_0[i]);
    for (i = 0; i < 3; i++)
      printf("  params.xt[%d] = %.6g;\n", i, params.xt[i]);
    for (i = 0; i < 9; i++)
      printf("  params.Q[%d] = %.6g;\n", i, params.Q[i]);
    for (i = 0; i < 1; i++)
      printf("  params.R[%d] = %.6g;\n", i, params.R[i]);
    for (i = 0; i < 6; i++)
      printf("  params.Fxs[%d] = %.6g;\n", i, params.Fxs[i]);
    for (i = 0; i < 2; i++)
      printf("  params.Fus[%d] = %.6g;\n", i, params.Fus[i]);
    for (i = 0; i < 2; i++)
      printf("  params.fs[%d] = %.6g;\n", i, params.fs[i]);
    for (i = 0; i < 9; i++)
      printf("  params.Q_final[%d] = %.6g;\n", i, params.Q_final[i]);
    for (i = 0; i < 9; i++)
      printf("  params.A[%d] = %.6g;\n", i, params.A[i]);
    for (i = 0; i < 3; i++)
      printf("  params.B[%d] = %.6g;\n", i, params.B[i]);
    for (i = 0; i < 3; i++)
      printf("  params.d[%d] = %.6g;\n", i, params.d[i]);
    for (i = 0; i < 12; i++)
      printf("  params.Fx[%d] = %.6g;\n", i, params.Fx[i]);
    for (i = 0; i < 4; i++)
      printf("  params.Fu[%d] = %.6g;\n", i, params.Fu[i]);
    for (i = 0; i < 4; i++)
      printf("  params.f[%d] = %.6g;\n", i, params.f[i]);
    for (i = 0; i < 6; i++)
      printf("  params.Ff[%d] = %.6g;\n", i, params.Ff[i]);
    for (i = 0; i < 2; i++)
      printf("  params.ff[%d] = %.6g;\n", i, params.ff[i]);
  }
  /* Perform the actual solve in here. */
  steps = solve();
  /* For profiling purposes, allow extra silent solves if desired. */
  settings.verbose = 0;
  for (i = 0; i < extra_solves; i++)
    solve();
  /* Update the status variables. */
  plhs[1] = mxCreateStructArray(1, dims1x1of1, 4, status_names);
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[1], 0, "optval", xm);
  *mxGetPr(xm) = work.optval;
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[1], 0, "gap", xm);
  *mxGetPr(xm) = work.gap;
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[1], 0, "steps", xm);
  *mxGetPr(xm) = steps;
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[1], 0, "converged", xm);
  *mxGetPr(xm) = work.converged;
  /* Extract variable values. */
  plhs[0] = mxCreateStructArray(1, dims1x1of1, num_var_names, var_names);
  /* Create cell arrays for indexed variables. */
  dims[0] = 9;
  cell = mxCreateCellArray(1, dims);
  mxSetField(plhs[0], 0, "u", cell);
  dims[0] = 10;
  cell = mxCreateCellArray(1, dims);
  mxSetField(plhs[0], 0, "x", cell);
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_0", xm);
  dest = mxGetPr(xm);
  src = vars.u_0;
  for (i = 0; i < 1; i++) {
    *dest++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_1", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 0, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_1;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_2", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 1, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_2;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_3", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 2, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_3;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_4", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 3, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_4;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_5", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 4, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_5;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_6", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 5, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_6;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_7", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 6, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_7;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_8", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 7, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_8;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(1, 1, mxREAL);
  mxSetField(plhs[0], 0, "u_9", xm);
  xm_cell = mxCreateDoubleMatrix(1, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "u");
  mxSetCell(cell, 8, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.u_9;
  for (i = 0; i < 1; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_1", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 0, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_1;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_2", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 1, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_2;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_3", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 2, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_3;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_4", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 3, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_4;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_5", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 4, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_5;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_6", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 5, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_6;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_7", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 6, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_7;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_8", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 7, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_8;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_9", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 8, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_9;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
  xm = mxCreateDoubleMatrix(3, 1, mxREAL);
  mxSetField(plhs[0], 0, "x_10", xm);
  xm_cell = mxCreateDoubleMatrix(3, 1, mxREAL);
  cell = mxGetField(plhs[0], 0, "x");
  mxSetCell(cell, 9, xm_cell);
  dest = mxGetPr(xm);
  dest_cell = mxGetPr(xm_cell);
  src = vars.x_10;
  for (i = 0; i < 3; i++) {
    *dest++ = *src;
    *dest_cell++ = *src++;
  }
}
コード例 #19
0
ファイル: subv2ind.c プロジェクト: brendonw1/PreBuzsaki
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
	int    i, j, k, nCol, nRow, binary, temp;
	double *pSize, *pSubv, *pr;
	int    *cumprod;

	pSize = mxGetPr(prhs[0]);
	pSubv = mxGetPr(prhs[1]);
	nCol  = mxGetNumberOfElements(prhs[0]);
	nRow  = mxGetM(prhs[1]);

	
	if(mxIsEmpty(prhs[1])){
		plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
		return;
	}

	if(mxIsEmpty(prhs[0])){
		plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
		*mxGetPr(plhs[0]) = 1;
		return;
	}

	binary = 2;
	for (i = 0; i < nCol; i++){
		if (pSize[i] > 2.0){
			binary = 0;
			break;
		}
		else if(pSize[i] == 1.0){
			binary = 1;
		}
	}

	plhs[0] = mxCreateDoubleMatrix(nRow, 1, mxREAL);
	pr = mxGetPr(plhs[0]);
	for(i=0; i<nRow; i++){
		pr[i] = 1.0;
	}

	if (binary == 2){
		for(j=0; j<nCol; j++){
			temp = j * nRow;
			for(i=0; i<nRow; i++){
				pr[i] += ((int)pSubv[temp + i] - 1) << j;
			}
		}
	}
	else if(binary == 1){	
		cumprod = malloc(nCol * sizeof(int));
		cumprod[0] = 1;
		for(i=1; i<nCol; i++){
			k = (int)pSize[i-1] - 1;
			cumprod[i] = cumprod[i-1] << k;
		}
		for(j=0; j<nCol; j++){
			temp = j * nRow;
			for(i=0; i<nRow; i++){
				k = (int)pSubv[temp + i] - 1;
				if(k)pr[i] += cumprod[j];
			}
		}
		free(cumprod);
	}
	else {
		cumprod = malloc(nCol * sizeof(int));
		cumprod[0] = 1;
		for(i=1; i<nCol; i++){
			k = (int)pSize[i-1];
			cumprod[i] = cumprod[i-1] * k;
		}
		for(j=0; j<nCol; j++){
			temp = j * nRow;
			for(i=0; i<nRow; i++){
				k = (int)pSubv[temp + i] - 1;
				pr[i] += cumprod[j] * k;
			}
		}
		free(cumprod);
	}
}
コード例 #20
0
ファイル: camd_mex.c プロジェクト: Al-th/matlab
void mexFunction
(
    int	nargout,
    mxArray *pargout [ ],
    int	nargin,
    const mxArray *pargin [ ]
)
{
    Long i, m, n, *Ap, *Ai, *P, nc, result, spumoni, full, *C, Clen ;
    double *Pout, *InfoOut, Control [CAMD_CONTROL], Info [CAMD_INFO],
	*ControlIn, *Cin ;
    mxArray *A ;

    /* --------------------------------------------------------------------- */
    /* get control parameters */
    /* --------------------------------------------------------------------- */

    camd_malloc = mxMalloc ;
    camd_free = mxFree ;
    camd_calloc = mxCalloc ;
    camd_realloc = mxRealloc ;
    camd_printf = mexPrintf ;

    spumoni = 0 ;
    if (nargin == 0)
    {
	/* get the default control parameters, and return */
	pargout [0] = mxCreateDoubleMatrix (CAMD_CONTROL, 1, mxREAL) ;
	camd_l_defaults (mxGetPr (pargout [0])) ;
	if (nargout == 0)
	{
	    camd_l_control (mxGetPr (pargout [0])) ;
	}
	return ;
    }

    camd_l_defaults (Control) ;
    if (nargin > 1)
    {
	ControlIn = mxGetPr (pargin [1]) ;
	nc = mxGetM (pargin [1]) * mxGetN (pargin [1]) ;
	Control [CAMD_DENSE]
	    = (nc > 0) ? ControlIn [CAMD_DENSE] : CAMD_DEFAULT_DENSE ;
	Control [CAMD_AGGRESSIVE]
	    = (nc > 1) ? ControlIn [CAMD_AGGRESSIVE] : CAMD_DEFAULT_AGGRESSIVE ;
	spumoni = (nc > 2) ? (ControlIn [2] != 0) : 0 ;
    }

    if (spumoni > 0)
    {
	camd_l_control (Control) ;
    }

    /* --------------------------------------------------------------------- */
    /* get inputs */
    /* --------------------------------------------------------------------- */

    if (nargout > 2 || nargin > 3)
    {
	mexErrMsgTxt ("Usage: p = camd (A)\n"
	    "or [p, Info] = camd (A, Control, C)") ;
    }

    Clen = 0 ;
    C = NULL ;
    if (nargin > 2)
    {
	Cin = mxGetPr (pargin [2]) ;
	Clen = mxGetNumberOfElements (pargin [2]) ;
	if (Clen != 0)
	{
	    C = (Long *) mxCalloc (Clen, sizeof (Long)) ;
	    for (i = 0 ; i < Clen ; i++)
	    {
		/* convert c from 1-based to 0-based */
		C [i] = (Long) Cin [i] - 1 ;
	    }
	}
    }

    A = (mxArray *) pargin [0] ;
    n = mxGetN (A) ;
    m = mxGetM (A) ;
    if (spumoni > 0)
    {
	mexPrintf ("    input matrix A is %d-by-%d\n", m, n) ;
    }

    if (mxGetNumberOfDimensions (A) != 2)
    {
	mexErrMsgTxt ("camd: A must be 2-dimensional") ;
    }
    if (m != n)
    {
    	mexErrMsgTxt ("camd: A must be square") ;
    }

    /* --------------------------------------------------------------------- */
    /* allocate workspace for output permutation */
    /* --------------------------------------------------------------------- */

    P = mxMalloc ((n+1) * sizeof (Long)) ;

    /* --------------------------------------------------------------------- */
    /* if A is full, convert to a sparse matrix */
    /* --------------------------------------------------------------------- */

    full = !mxIsSparse (A) ;
    if (full)
    {
	if (spumoni > 0)
	{
	    mexPrintf (
	    "    input matrix A is full (sparse copy of A will be created)\n");
	}
	mexCallMATLAB (1, &A, 1, (mxArray **) pargin, "sparse") ;
    }
    Ap = (Long *) mxGetJc (A) ;
    Ai = (Long *) mxGetIr (A) ;
    if (spumoni > 0)
    {
	mexPrintf ("    input matrix A has %d nonzero entries\n", Ap [n]) ;
    }

    /* --------------------------------------------------------------------- */
    /* order the matrix */
    /* --------------------------------------------------------------------- */

    result = camd_l_order (n, Ap, Ai, P, Control, Info, C) ;

    /* --------------------------------------------------------------------- */
    /* if A is full, free the sparse copy of A */
    /* --------------------------------------------------------------------- */

    if (full)
    {
	mxDestroyArray (A) ;
    }

    /* --------------------------------------------------------------------- */
    /* print results (including return value) */
    /* --------------------------------------------------------------------- */

    if (spumoni > 0)
    {
	camd_l_info (Info) ;
    }

    /* --------------------------------------------------------------------- */
    /* check error conditions */
    /* --------------------------------------------------------------------- */

    if (result == CAMD_OUT_OF_MEMORY)
    {
	mexErrMsgTxt ("camd: out of memory") ;
    }
    else if (result == CAMD_INVALID)
    {
	mexErrMsgTxt ("camd: input matrix A is corrupted") ;
    }

    /* --------------------------------------------------------------------- */
    /* copy the outputs to MATLAB */
    /* --------------------------------------------------------------------- */

    /* output permutation, P */
    pargout [0] = mxCreateDoubleMatrix (1, n, mxREAL) ;
    Pout = mxGetPr (pargout [0])  ;
    for (i = 0 ; i < n ; i++)
    {
	Pout [i] = P [i] + 1 ;	    /* change to 1-based indexing for MATLAB */
    }
    mxFree (P) ;
    if (nargin > 2) mxFree (C) ;

    /* Info */
    if (nargout > 1)
    {
	pargout [1] = mxCreateDoubleMatrix (CAMD_INFO, 1, mxREAL) ;
	InfoOut = mxGetPr (pargout [1]) ;
	for (i = 0 ; i < CAMD_INFO ; i++)
	{
	    InfoOut [i] = Info [i] ;
	}
    }
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
        nTupleVolume<float> *imgVol, *occVol, 
                *gradXvol, *gradYvol, *normGradXvol, *normGradYvol, *dispField;
        int * imgVolSizes, *dispFieldSizes;
        float sigmaColour;
        float *dispFieldTemp;
        int numDimsImgVol, numDimsDispField;
        int useAllPatches, reconstructionType;
        parameterStruct *patchMatchParams;
        mwSize resultSize[4];
        
        if (nrhs < (SIGMA_COLOUR_INPUT+1))
        {
            mexErrMsgTxt("Error. A minimum of 10 parameters are needed in the spatio-temporal patch match mexfunction.\n");
            return;
        }

        ASSERT ( (mxGetClassID(prhs[IMG_VOL_INPUT]) == mxSINGLE_CLASS) & (mxGetClassID(prhs[OCC_VOL_INPUT]) == mxSINGLE_CLASS)
                 & (mxGetClassID(prhs[DISP_FIELD_INPUT]) == mxSINGLE_CLASS));

        /* Get sizes of variables*/
        imgVolSizes = (int*)mxGetDimensions(prhs[IMG_VOL_INPUT]);  /* sizes of imgVol*/
        numDimsImgVol = (int)mxGetNumberOfDimensions(prhs[IMG_VOL_INPUT]);  /*length of sizes of imgVolA*/
        dispFieldSizes = (int*)mxGetDimensions(prhs[DISP_FIELD_INPUT]);  /*sizes of imgVolB*/
        numDimsDispField = (int)mxGetNumberOfDimensions(prhs[DISP_FIELD_INPUT]);  /* length of sizes of dispField*/
        
        if ((numDimsImgVol != 4) || (numDimsDispField != 4))
        {
            mexPrintf("Number of dimensions :\n imgVol : %d\nimgVolFine : %d\nDispField : %d\n",numDimsImgVol,numDimsDispField);
            mexErrMsgTxt("Error, the number of array dimensions must be 4 (x,y,t,multivalue).");
			plhs[0] = mxCreateNumericMatrix((mwSize)1,(mwSize)1, mxINT32_CLASS, (mxComplexity)0);
            dispFieldTemp = (float*)mxGetPr(plhs[0]);
            *dispFieldTemp = -1;
            return;
        }
		
        //get the patchMatch parameters
        ASSERT(mxIsStruct(prhs[PATCH_MATCH_PARAMS_INPUT]) );
        patchMatchParams = (parameterStruct*)new parameterStruct;
        parse_patch_match_parameters(prhs[PATCH_MATCH_PARAMS_INPUT],patchMatchParams);
        /* sigma colour*/
        sigmaColour = (float)(*mxGetPr(prhs[SIGMA_COLOUR_INPUT]));  
        
        if ( (imgVolSizes[2] < patchMatchParams->patchSizeX) || (imgVolSizes[1] < patchMatchParams->patchSizeY) || (imgVolSizes[3] < patchMatchParams->patchSizeT) )
        {
            MY_PRINTF("Image sizes :\n x : %d, y : %d, t : %d\n",(int)imgVolSizes[2],(int)imgVolSizes[1],(int)imgVolSizes[3]);
            MY_PRINTF("Patch sizes :\n x : %d, y : %d, t : %d\n",(int)patchMatchParams->patchSizeX,(int)patchMatchParams->patchSizeY,(int)patchMatchParams->patchSizeT);
            mexErrMsgTxt("Error, the patch sizes are too large for the image.");
			plhs[0] = mxCreateNumericMatrix((mwSize)1,(mwSize)1, mxINT32_CLASS, (mxComplexity)0);
            dispFieldTemp = (float*)mxGetPr(plhs[0]);
            *dispFieldTemp = -1;
            return;
        }
        
        
        if (nrhs >= (USE_ALL_PATCHES_INPUT+1))
            useAllPatches = (int)(*mxGetPr(prhs[USE_ALL_PATCHES_INPUT]));  /* if we want to use all surrounding patches or not*/
        else
            useAllPatches = 1;
        
        if (nrhs >= (RECONSTRUCTION_TYPE_INPUT+1))
            reconstructionType = (int)(*mxGetPr(prhs[RECONSTRUCTION_TYPE_INPUT]));  /* the manner in which we want to reconstruct the image*/
        else
            reconstructionType = 0;

        
        int imageIndexing = 1;
        //input image volumes
        imgVol = new nTupleVolume<float>(3, (int)imgVolSizes[2], (int)imgVolSizes[1], (int)imgVolSizes[3],
                patchMatchParams->patchSizeX, patchMatchParams->patchSizeY, patchMatchParams->patchSizeT,imageIndexing,
            (float*)mxGetPr(prhs[IMG_VOL_INPUT]));
        occVol = new nTupleVolume<float>(1, (int)imgVolSizes[2], (int)imgVolSizes[1], (int)imgVolSizes[3],
                patchMatchParams->patchSizeX, patchMatchParams->patchSizeY, patchMatchParams->patchSizeT,imageIndexing,
                (float*)mxGetPr(prhs[OCC_VOL_INPUT]));
        
        //shift volume
        dispField = new nTupleVolume<float>(4, (int)imgVolSizes[2], (int)imgVolSizes[1], (int)imgVolSizes[3],
                patchMatchParams->patchSizeX, patchMatchParams->patchSizeY, patchMatchParams->patchSizeT,imageIndexing,
            (float*)mxGetPr(prhs[DISP_FIELD_INPUT]));
        
        //features
        gradXvol = new nTupleVolume<float>(1, (int)imgVolSizes[2], (int)imgVolSizes[1], (int)imgVolSizes[3],
                patchMatchParams->patchSizeX, patchMatchParams->patchSizeY, patchMatchParams->patchSizeT,imageIndexing,
                (float*)patchMatchParams->gradX);
        gradYvol = new nTupleVolume<float>(1, (int)imgVolSizes[2], (int)imgVolSizes[1], (int)imgVolSizes[3],
                patchMatchParams->patchSizeX, patchMatchParams->patchSizeY, patchMatchParams->patchSizeT,imageIndexing,
                (float*)patchMatchParams->gradY);
        normGradXvol = new nTupleVolume<float>(1, (int)imgVolSizes[2], (int)imgVolSizes[1], (int)imgVolSizes[3],
                patchMatchParams->patchSizeX, patchMatchParams->patchSizeY, patchMatchParams->patchSizeT,imageIndexing,
                (float*)patchMatchParams->normGradX);
        normGradYvol = new nTupleVolume<float>(1, (int)imgVolSizes[2], (int)imgVolSizes[1], (int)imgVolSizes[3],
                patchMatchParams->patchSizeX, patchMatchParams->patchSizeY, patchMatchParams->patchSizeT,imageIndexing,
                (float*)patchMatchParams->normGradY);
        
        /*colour estimation*/
        reconstruct_videos(imgVol, occVol,
            gradXvol, gradYvol, normGradXvol, normGradYvol,
            dispField, (float)sigmaColour, useAllPatches, reconstructionType);
        
        /*OUTPUT*/
        /* Create output matrix*/
        resultSize[0] = (int)(imgVolSizes[0]);
        resultSize[1] = (int)(imgVolSizes[1]);
        resultSize[2] = (int)(imgVolSizes[2]);
        resultSize[3] = (int)(imgVolSizes[3]);
        plhs[0] = mxCreateNumericArray((mwSize)4,(mwSize*)resultSize, mxSINGLE_CLASS, (mxComplexity)0);
        float *imgVolOutTemp = (float*)mxGetPr(plhs[0]);
        memcpy(imgVolOutTemp,imgVol->get_value_ptr( 0,0,0,0), resultSize[0]*resultSize[1]*resultSize[2]*resultSize[3]*sizeof(float));
        
        
        //create other output matrices
        resultSize[0] = (int)(imgVolSizes[1]);
        resultSize[1] = (int)(imgVolSizes[2]);
        resultSize[2] = (int)(imgVolSizes[3]);
        
        plhs[1] = mxCreateNumericArray((mwSize)3,(mwSize*)resultSize, mxSINGLE_CLASS, (mxComplexity)0);
        float* gradXoutTemp = (float*)mxGetPr(plhs[1]);
        memcpy(gradXoutTemp,gradXvol->get_value_ptr( 0,0,0,0), resultSize[0]*resultSize[1]*resultSize[2]*sizeof(float));
        
        plhs[2] = mxCreateNumericArray((mwSize)3,(mwSize*)resultSize, mxSINGLE_CLASS, (mxComplexity)0);
        float* gradYoutTemp = (float*)mxGetPr(plhs[2]);
        memcpy(gradYoutTemp,gradYvol->get_value_ptr( 0,0,0,0), resultSize[0]*resultSize[1]*resultSize[2]*sizeof(float));
        
        plhs[3] = mxCreateNumericArray((mwSize)3,(mwSize*)resultSize, mxSINGLE_CLASS, (mxComplexity)0);
        float* normGradXoutTemp = (float*)mxGetPr(plhs[3]);
        memcpy(normGradXoutTemp,normGradXvol->get_value_ptr( 0,0,0,0), resultSize[0]*resultSize[1]*resultSize[2]*sizeof(float));
        
        plhs[4] = mxCreateNumericArray((mwSize)3,(mwSize*)resultSize, mxSINGLE_CLASS, (mxComplexity)0);
        float* normGradYoutTemp = (float*)mxGetPr(plhs[4]);
        memcpy(normGradYoutTemp,normGradYvol->get_value_ptr( 0,0,0,0), resultSize[0]*resultSize[1]*resultSize[2]*sizeof(float));
        
        delete imgVol;
        delete gradXvol;
        delete gradYvol;
        delete normGradXvol;
        delete normGradYvol;
        delete patchMatchParams;
        
        return;
}
コード例 #22
0
void Project_Engine::Matlab_execution()
{
	Engine	*ep;
	mxArray *cust_array					= mxCreateDoubleMatrix(CUSTOMERS_MAX-1,1,mxREAL);
	mxArray *mov_avg_array				= mxCreateDoubleMatrix(MOVIES_MAX-1,1,mxREAL);
	mxArray *mov_count_array			= mxCreateDoubleMatrix(MOVIES_MAX-1,1,mxREAL);
	double	*p_rating_count				= mxGetPr(cust_array);
	double	*p_movie_avg				= mxGetPr(mov_avg_array);
	double	*p_mov_count				= mxGetPr(mov_count_array);
	int		i,j,counter;
	float	Current_movie,Current_cust;
	intHashTable*	movie_average		= new intHashTable(9);
	intHashTable*	user_average		= new intHashTable(9);

//======================USER AVERAGE DISTRIBUTION======================
	for (i=1;i<CUSTOMERS_MAX;i++){
		//Round up each customer rating average to the nearest 0.5 between 1 and 5
		Current_cust = floor((2*Customer_spec[i].Cust_RateAvg)+0.5)/2;
		for (j=0;j<9;j++){
			if (Current_cust<(1+0.5*j)){
					//According to the users rounded average, the corresponding id is inserted into a specific rating list 
					user_average->insert(i,Current_cust,j);
					break;
			}
		}
	}

mxArray *custrating_array	= mxCreateDoubleMatrix(9,1,mxREAL);
mxArray *custcount_array	= mxCreateDoubleMatrix(9,1,mxREAL);
double *pcustx				= mxGetPr(custrating_array);
double *pcusty				= mxGetPr(custcount_array);
Node** user_table			= user_average->getTable();

for (j=0;j<9;j++){
		counter = 0;
		pcustx[j] = 1+0.5*j;
		while(user_table[j]!=NULL){
			counter++;
			user_table[j] = user_table[j]->Next;
		}
		pcusty[j] = counter;
	}
memcpy((void*)mxGetPr(custrating_array),	(void*)pcustx, (9)*sizeof(float));
memcpy((void*)mxGetPr(custcount_array),		(void*)pcusty, (9)*sizeof(float));
//======================USER AVERAGE DISTRIBUTION======================

//======================MOVIE AVERAGE DISTRIBUTION======================
	for (i=1;i<MOVIES_MAX;i++){
		Current_movie = floor((2*Movie_spec[i].Movie_RateAvg)+0.5)/2;
		for (j=0;j<9;j++){
			if (Current_movie<(1+0.5*j)){
					movie_average->insert(i,Current_movie,j);
					break;
				}
		}
	}

mxArray *mrating_array	= mxCreateDoubleMatrix(9,1,mxREAL);
mxArray *mcount_array	= mxCreateDoubleMatrix(9,1,mxREAL);
double *px				= mxGetPr(mrating_array);
double *py				= mxGetPr(mcount_array);
Node** movie_table		= movie_average->getTable();

for (j=0;j<9;j++){
		counter = 0;
		px[j] = 1+0.5*j;
		while(movie_table[j]!=NULL){
			counter++;
			movie_table[j] = movie_table[j]->Next;
		}
		py[j] = counter;
	}
memcpy((void*)mxGetPr(mrating_array),	(void*)px, (9)*sizeof(float));
memcpy((void*)mxGetPr(mcount_array),	(void*)py, (9)*sizeof(float));
//======================MOVIE AVERAGE DISTRIBUTION======================	

	if (!(ep = engOpen("\0")))
		cerr << "Cant start MATLAB engine" << endl;

	for (i=1;i<CUSTOMERS_MAX;i++){
		p_rating_count[i-1]	=	Customer_spec[i].Cust_RateCount;		
	 };

	for (i=1;i<MOVIES_MAX;i++){
		p_movie_avg[i-1]		=	Movie_spec[i].Movie_RateAvg;
		p_mov_count[i-1]		=	Movie_spec[i].Movie_RateCount;
	 };

memcpy((void*)mxGetPr(cust_array),		(void*)p_rating_count,	(CUSTOMERS_MAX-1)*sizeof(float));
memcpy((void*)mxGetPr(mov_avg_array),	(void*)p_movie_avg,		(MOVIES_MAX-1)*sizeof(float));
memcpy((void*)mxGetPr(mov_count_array), (void*)p_mov_count,		(MOVIES_MAX-1)*sizeof(float));

engPutVariable(ep,"rating_count",cust_array);
engPutVariable(ep,"movie_avg"	,mov_avg_array);
engPutVariable(ep,"mov_count"	,mov_count_array);

engEvalString(ep, "figure(1);");
engEvalString(ep, "B=sort(rating_count);");
engEvalString(ep, "numberOfBins = 100;[counts, binValues] = hist(B, numberOfBins);normalizedCounts = 100 * counts / sum(counts);");
engEvalString(ep, "bar(sort(binValues),normalizedCounts,'r');set(gca,'XTick', []);");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Customer Rating Count Distribution')");
engEvalString(ep, "ylabel('Rating Count [%]')");

engEvalString(ep, "figure(2);");
engEvalString(ep, "B=sort(movie_avg);plot(B,'-.r*');");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Movie Average Distribution')");
engEvalString(ep, "xlabel('Movie ID')");
engEvalString(ep, "ylabel('Rating Average')");

engEvalString(ep, "figure(3);");
engEvalString(ep, "C=sort(mov_count);");
engEvalString(ep, "numberOfBins = 100;[counts, binValues] = hist(C, numberOfBins);normalizedCounts = 100 * counts / sum(counts);");
engEvalString(ep, "bar(sort(binValues),normalizedCounts);");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Movie Rating Count Distribution')");
engEvalString(ep, "ylabel('Rating Count [%]')");

engPutVariable(ep,"x",mrating_array);
engPutVariable(ep,"y",mcount_array);

engPutVariable(ep,"custx",custrating_array);
engPutVariable(ep,"custy",custcount_array);

engEvalString(ep, "figure(4);");
engEvalString(ep, "bar(x,y/sum(y));");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Average Rating Distribution of Movies')");
engEvalString(ep, "xlabel('Rating')");
engEvalString(ep, "ylabel('Density')");
engEvalString(ep, "hold on");
engEvalString(ep, "plot(custx,custy/sum(custy),'--r','LineWidth',2);");
engEvalString(ep, "hold off");

string s;
cout << "Press Any Key to exit MATLAB and continue the program:" << endl;
getline(cin, s);
mxDestroyArray(cust_array);
mxDestroyArray(mov_avg_array);
mxDestroyArray(mov_count_array);
engEvalString(ep,"close;");
}
コード例 #23
0
unsigned int sf_ARP_01_lib_TruthTables_process_check_sum_call( int nlhs, mxArray
  * plhs[], int nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(270255544U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3961473453U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1009897709U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2488429771U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(368048769U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3016083928U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3250039828U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(6240571U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 3:
        {
          extern void sf_c3_ARP_01_lib_TruthTables_get_check_sum(mxArray *plhs[]);
          sf_c3_ARP_01_lib_TruthTables_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(814460797U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(400623215U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1072597456U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1176453921U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2788616998U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2487330489U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1761348596U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(660782654U);
  }

  return 1;

#else

  return 0;

#endif

}
コード例 #24
0
unsigned int sf_testRPSsmile_Glove_Idle_process_check_sum_call( int nlhs,
  mxArray * plhs[], int nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2045635351U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2715586075U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3111568814U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1159579284U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3320639127U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2129564017U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3931394745U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3916111457U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 1:
        {
          extern void sf_c1_testRPSsmile_Glove_Idle_get_check_sum(mxArray *plhs[]);
          sf_c1_testRPSsmile_Glove_Idle_get_check_sum(plhs);
          break;
        }

       case 2:
        {
          extern void sf_c2_testRPSsmile_Glove_Idle_get_check_sum(mxArray *plhs[]);
          sf_c2_testRPSsmile_Glove_Idle_get_check_sum(plhs);
          break;
        }

       case 3:
        {
          extern void sf_c3_testRPSsmile_Glove_Idle_get_check_sum(mxArray *plhs[]);
          sf_c3_testRPSsmile_Glove_Idle_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3631444906U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1375517235U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1750316125U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(284886239U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1133909972U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1291780845U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1524668069U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1317510692U);
  }

  return 1;

#else

  return 0;

#endif

}
コード例 #25
0
/*
 * The mex function runs a max-flow min-cut problem.
 */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    int i;
    
    int mrows, ncols;
    
    int n,nz;
    
    /* sparse matrix */
    mwIndex *ia, *ja;
    
    
    /* output data */
    double *a, *ci;
    mwIndex *int_a;
     
    
    if (nrhs != 1) 
    {
        mexErrMsgTxt("1 inputs required.");
    }

    /* The first input must be a sparse matrix. */
    mrows = mxGetM(prhs[0]);
    ncols = mxGetN(prhs[0]);
    if (mrows != ncols ||
        !mxIsSparse(prhs[0]) ||
        !mxIsDouble(prhs[0]) || 
        mxIsComplex(prhs[0])) 
    {
        mexErrMsgTxt("Input must be a noncomplex square sparse matrix.");
    }
    
    n = mrows;
        
    
    
    /* Get the sparse matrix */
    
    /* recall that we've transposed the matrix */
    ja = mxGetIr(prhs[0]);
    ia = mxGetJc(prhs[0]);
    
    nz = ia[n];
        
    plhs[0] = mxCreateDoubleMatrix(n,1,mxREAL);
    a = mxGetPr(plhs[0]);
    ci = NULL;
    
    if (nlhs > 1)
    {
        plhs[1] = mxCreateDoubleMatrix(nz,1,mxREAL);
        ci = mxGetPr(plhs[1]);
    }
    
    int_a = (mwIndex*)a;
    for (i=0; i<n; i++)
    {
        int_a[i] = MWINDEX_MAX;
    }
    
    
    biconnected_components(n, ja, ia,
        (mwIndex*)a, (mwIndex*)ci);
    
    expand_index_to_double_zero_special((mwIndex*)a, a, n, 1.0, MWINDEX_MAX);
    if (nlhs > 1)
    {
        expand_index_to_double((mwIndex*)ci, ci, nz, 1.0);
    }
}
コード例 #26
0
ファイル: vtomat.c プロジェクト: Rollmops/lipsia
int
main(int argc, char *argv[]) {
    /* Command line options: */
    static VString mat = NULL;
    static VBoolean funconly = FALSE;
    static VOptionDescRec  options[] = {
        {"out", VStringRepn, 1, &mat, VRequiredOpt, 0, "Matfile"},
        {"funconly", VBooleanRepn, 1, &funconly, VOptionalOpt, 0, "Functional data only (in one single 4D-object)"},
    };
    FILE *in_file;
    VAttrList in_list;
    VAttrListPosn posn;
    VImage src = NULL;
    VBit     *bit_pp = NULL, *pbSRC = NULL;
    VShort *short_pp = NULL, *psSRC = NULL;
    VUByte *ubyte_pp = NULL, *puSRC = NULL;
    VFloat *float_pp = NULL, *pfSRC = NULL;
    VDouble *double_pp = NULL, *pdSRC = NULL;
    VString mode = NULL, name = NULL;
    mxArray *SRC = NULL;
    MATFile *fp;
    int n = 0, dims[4];
    int bands = 0, rows = 0, cols = 0;
    char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vtomat V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /* Parse command line arguments and identify files: */
    VParseFilterCmd(VNumber(options), options, argc, argv, &in_file,/* &out_file */ NULL);
    /* Read the input file */
    in_list = VReadFile(in_file, NULL);
    if(!in_list)
        exit(1);
    /* strings */
    mode = (VString)malloc(sizeof(char));
    name = (VString)malloc(sizeof(char) * 50);
    strcpy(mode, "w");
    fp = matOpen(mat, mode);
    if(funconly == TRUE) {
        /*******************************************************************
         *                                                                 *
         *                   L O O P over objects in vista file            *
         *                                                                 *
         *******************************************************************/
        n = 0;
        for(VFirstAttr(in_list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            if(VPixelRepn(src) == VShortRepn) {
                if(bands < 2)
                    bands = VImageNBands(src);
                if(rows  < 2)
                    rows  = VImageNRows(src);
                if(cols  < 2)
                    cols  = VImageNColumns(src);
                if(bands != VImageNBands(src))
                    VError("Different bands in functional objects");
                if(rows  != VImageNRows(src))
                    VError("Different rows  in functional objects");
                if(cols  != VImageNColumns(src))
                    VError("Different cols  in functional objects");
                n++;
            }
        }
        /*dimensions */
        dims[3] = n;
        dims[2] = bands;
        dims[1] = rows;
        dims[0] = cols;
        SRC   = mxCreateNumericArray(4, dims, mxINT16_CLASS, mxREAL);
        psSRC = (VShort *) mxGetPr(SRC);
        /* copy data to SRC */
        for(VFirstAttr(in_list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            if(VPixelRepn(src) == VShortRepn) {
                short_pp = (VShort *) VPixelPtr(src, 0, 0, 0);
                memcpy(psSRC, short_pp, sizeof(VShort) * dims[0] * dims[1] * dims[2]);
                psSRC += dims[0] * dims[1] * dims[2];
            }
        }
        /* save data into file */
        if(matPutVariable(fp, "fnc", SRC))
            VError("Could not save data in MATLAB file");
        /* destroy array */
        mxDestroyArray(SRC);
    } else {
        /*******************************************************************
         *                                                                 *
         *                   L O O P over objects in vista file            *
         *                                                                 *
         *******************************************************************/
        n = 0;
        for(VFirstAttr(in_list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            /*dimensions */
            dims[3] = 1;
            dims[2] = VImageNBands(src);
            dims[1] = VImageNRows(src);
            dims[0] = VImageNColumns(src);
            sprintf(name, "obj%d\0", n);
            /* Bit ONLY */
            if(VPixelRepn(src) == VBitRepn) {
                SRC    = mxCreateNumericArray(3, dims, mxLOGICAL_CLASS, mxREAL);
                pbSRC  = (VBit *) mxGetPr(SRC);
                bit_pp = (VBit *) VPixelPtr(src, 0, 0, 0);
                memcpy(pbSRC, bit_pp, sizeof(VBit) * dims[0] * dims[1] * dims[2]);
            }
            /* Short ONLY */
            if(VPixelRepn(src) == VShortRepn) {
                SRC      = mxCreateNumericArray(3, dims, mxINT16_CLASS, mxREAL);
                psSRC    = (VShort *) mxGetPr(SRC);
                short_pp = (VShort *) VPixelPtr(src, 0, 0, 0);
                memcpy(psSRC, short_pp, sizeof(VShort) * dims[0] * dims[1] * dims[2]);
            }
            /* UByte ONLY */
            if(VPixelRepn(src) == VUByteRepn) {
                SRC      = mxCreateNumericArray(3, dims, mxUINT8_CLASS, mxREAL);
                puSRC    = (VUByte *) mxGetPr(SRC);
                ubyte_pp = (VUByte *) VPixelPtr(src, 0, 0, 0);
                memcpy(puSRC, ubyte_pp, sizeof(VUByte) * dims[0] * dims[1] * dims[2]);
            }
            /* Float ONLY */
            if(VPixelRepn(src) == VFloatRepn) {
                SRC      = mxCreateNumericArray(3, dims, mxSINGLE_CLASS, mxREAL);
                pfSRC    = (VFloat *) mxGetPr(SRC);
                float_pp = (VFloat *) VPixelPtr(src, 0, 0, 0);
                memcpy(pfSRC, float_pp, sizeof(VFloat) * dims[0] * dims[1] * dims[2]);
            }
            /* Double ONLY */
            if(VPixelRepn(src) == VDoubleRepn) {
                SRC       = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
                pdSRC     = (VDouble *) mxGetPr(SRC);
                double_pp = (VDouble *) VPixelPtr(src, 0, 0, 0);
                memcpy(pdSRC, double_pp, sizeof(VDouble) * dims[0] * dims[1] * dims[2]);
            }
            /* save data into file */
            if(matPutVariable(fp, name, SRC))
                VError("Could not save data in MATLAB file");
            /* destroy array */
            mxDestroyArray(SRC);
            n++;
        }
    }
    /* Terminate */
    matClose(fp);
    return 0;
}
コード例 #27
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    #define facesInput prhs[0]
    #define verticesInput prhs[1]

    #define edgesOutput plhs[0]
    #define edgeLengthsOutput plhs[1]
    #define edgeUnitsOutput plhs[2]
    #define edgeCentersOutput plhs[3]
    #define edgeNormalsOutput plhs[4]
    #define faceNormalsOutput plhs[5]
    #define faceAreasOutput plhs[6]
    #define volumeOutput plhs[7]

    mxArray *faceCell, *edgesCell, *edgeCentersCell, *edgeLengthsCell, 
            *edgeUnitsCell, *faceNormalCell, *edgeNormalsCell;
    double *face, *vertices, *edges, *edgeCenters, *edgeLengths,
           *edgeUnits, *faceNormal, *edgeNormals, *faceAreas, *volume;
    double tmp;
    mwIndex f, e, i;
    mwIndex currentVertexIdx, nextVertexIdx, edgeIdx;
    mwSize faceNumber, edgeNumber, vertexNumber;
    mwSize edgesOutputSize[EDGES_OUTPUT_DIM];

    if (nrhs != 2)
        mexErrMsgTxt("There should be exactly two inputs, faces and vertices.");
    if (nlhs != 8)
        mexErrMsgTxt("There should be exactly 8 outputs. "
            "edges, edgeLengths, edgeCenters, edgeUnits, edgeCenters, "
            "edgeNormals, faceNormals.");
    if (!mxIsCell(facesInput))
        mexErrMsgTxt("Input faces should be a cell array!");
    if (!mxIsDouble(verticesInput))
        mexErrMsgTxt("Input vertices should be a double matrix!");
                
    faceNumber = mxGetNumberOfElements(facesInput);
    vertices = mxGetPr(verticesInput);
    vertexNumber = mxGetN(verticesInput);

    edgesOutputSize[0] = faceNumber;
    edgesOutputSize[1] = 1;

    edgesOutput = mxCreateCellArray(EDGES_OUTPUT_DIM, edgesOutputSize);
    edgeLengthsOutput = mxCreateCellArray(EDGES_OUTPUT_DIM, edgesOutputSize);
    edgeUnitsOutput = mxCreateCellArray(EDGES_OUTPUT_DIM, edgesOutputSize);
    edgeCentersOutput = mxCreateCellArray(EDGES_OUTPUT_DIM, edgesOutputSize);
    edgeNormalsOutput = mxCreateCellArray(EDGES_OUTPUT_DIM, edgesOutputSize);
    faceNormalsOutput = mxCreateCellArray(EDGES_OUTPUT_DIM, edgesOutputSize);
    faceAreasOutput = mxCreateDoubleMatrix(faceNumber, 1, mxREAL); 
    faceAreas = mxGetPr(faceAreasOutput);
    volumeOutput = mxCreateDoubleMatrix(1, 1, mxREAL); 
    volume = mxGetPr(volumeOutput);

    for (f = 0; f < faceNumber; f++)
    {
        faceCell = mxGetCell(facesInput, f);
        face = mxGetPr(faceCell);

        edgeNumber = (mwIndex)(mxGetN(faceCell)) - 1; 
            // face is 1 by e + 1 array, the last entry is duplication of
            // the first one

        edgesCell = mxCreateDoubleMatrix(dim, edgeNumber, mxREAL);
        edges = mxGetPr(edgesCell);

        edgeCentersCell = mxCreateDoubleMatrix(dim, edgeNumber, mxREAL);
        edgeCenters = mxGetPr(edgeCentersCell);

        edgeLengthsCell = mxCreateDoubleMatrix(1, edgeNumber, mxREAL);
        edgeLengths = mxGetPr(edgeLengthsCell);

        edgeUnitsCell = mxCreateDoubleMatrix(dim, edgeNumber, mxREAL);
        edgeUnits = mxGetPr(edgeUnitsCell);

        edgeNormalsCell = mxCreateDoubleMatrix(dim, edgeNumber, mxREAL);
        edgeNormals = mxGetPr(edgeNormalsCell);

        faceNormalCell = mxCreateDoubleMatrix(dim, 1, mxREAL);
        faceNormal = mxGetPr(faceNormalCell);

        for (e = 0; e < edgeNumber; e++)
        {
            for (i = 0; i < dim; i++)
            {
                nextVertexIdx = (mwIndex)face[e+1] * dim + i;
                currentVertexIdx = (mwIndex)face[e] * dim + i;

                edgeIdx = dim * e + i;

                edgeCenters[edgeIdx] = (vertices[nextVertexIdx] 
                    + vertices[currentVertexIdx]) / 2;
                edges[edgeIdx] = vertices[nextVertexIdx] 
                    - vertices[currentVertexIdx];
            }
            edgeLengths[e] = twoNorm(edges + e * dim, dim);

            for (i = 0; i < dim; i++)
            {
                edgeIdx = dim * e + i;
                edgeUnits[edgeIdx] = edges[edgeIdx] / edgeLengths[e];
            }
        }
        cross(edgeUnits, edgeUnits + dim, faceNormal); 
        mexPrint1dArray(faceNormal, dim);
        tmp = twoNorm(faceNormal, dim);
        divideScaler(faceNormal, dim, tmp);

        faceAreas[f] = calcFaceArea(vertices, vertexNumber, face,
            edgeNumber, faceNormal);

        for (e = 0; e < edgeNumber; e++){
            cross(edgeUnits + e * dim, faceNormal, edgeNormals + e * dim);
            for (i = 0; i < dim; i++){
                edgeNormals[e * dim + i] *= edgeLengths[e];
            }
        }
        mxSetCell(edgesOutput, f, edgesCell);
        mxSetCell(edgeCentersOutput, f, edgeCentersCell);
        mxSetCell(edgeLengthsOutput, f, edgeLengthsCell);
        mxSetCell(edgeUnitsOutput, f, edgeUnitsCell);
        mxSetCell(faceNormalsOutput, f, faceNormalCell);
        mxSetCell(edgeNormalsOutput, f, edgeNormalsCell);
    }
    *volume = calcPolyVolumeCellFaces(faceAreas, vertices, facesInput, 
        faceNormalsOutput);
}
コード例 #28
0
unsigned int sf_AtomicGloveBradImitateSmile_process_check_sum_call( int nlhs,
  mxArray * plhs[], int nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1062503932U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(662950597U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(426861474U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(980732289U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1409942318U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2158479853U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(595887718U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(617325940U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 1:
        {
          extern void sf_c1_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c1_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       case 2:
        {
          extern void sf_c2_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c2_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       case 3:
        {
          extern void sf_c3_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c3_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       case 4:
        {
          extern void sf_c4_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c4_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       case 5:
        {
          extern void sf_c5_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c5_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       case 6:
        {
          extern void sf_c6_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c6_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       case 7:
        {
          extern void sf_c7_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c7_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       case 8:
        {
          extern void sf_c8_AtomicGloveBradImitateSmile_get_check_sum(mxArray
            *plhs[]);
          sf_c8_AtomicGloveBradImitateSmile_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3631444906U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1375517235U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1750316125U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(284886239U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2491497851U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3738371599U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(754644313U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2868274962U);
  }

  return 1;

#else

  return 0;

#endif

}
コード例 #29
0
ファイル: libqp_gsmo_mex.c プロジェクト: AAAyag/clandmark
/* -------------------------------------------------------------------
 Main MEX function - interface to Matlab.

  [vec_x,exitflag,t,access,Nabla] = 
         gsmo_mex(H,f,a,b,LB,UB,x0,Nabla0,tmax,tolKKT,verb);

-------------------------------------------------------------------- */
void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray*prhs[] )
{
  int verb;          
  uint32_t i;         
  uint32_t MaxIter;   
  double TolKKT; 
  double *vec_x;         /* output arg -- solution*/ 
  double *vec_x0;         
  double *diag_H;    /* diagonal of matrix H */
  double *f;         /* vector f */
  double *a;
  double b;
  double *LB;
  double *UB;
  double fval;
  
  /*------------------------------------------------------------------- */
  /* Take input arguments                                               */
  /*------------------------------------------------------------------- */

  if( nrhs != 10) mexErrMsgTxt("Incorrect number of input arguments.");

  mat_H = mxGetPr(prhs[0]);
  nVar = mxGetM(prhs[0]);
  f = mxGetPr(prhs[1]);   
  a = mxGetPr(prhs[2]);
  b = mxGetScalar(prhs[3]);
  LB = mxGetPr(prhs[4]);
  UB = mxGetPr(prhs[5]);
  vec_x0 = mxGetPr(prhs[6]);
  MaxIter = mxIsInf( mxGetScalar(prhs[7])) ? INT_MAX : (long)mxGetScalar(prhs[7]);
  TolKKT = mxGetScalar(prhs[8]); 
  verb = (int)(mxGetScalar(prhs[9])); 
    
  if( verb > 0 ) {
    mexPrintf("Settings of QP solver\n");
    mexPrintf("MaxIter : %d\n", MaxIter );
    mexPrintf("TolKKT  : %f\n", TolKKT );
    mexPrintf("nVar    : %d\n", nVar );
    mexPrintf("verb    : %d\n", verb );
  }

  plhs[0] = mxCreateDoubleMatrix(nVar,1,mxREAL);
  vec_x = mxGetPr(plhs[0]);
  memcpy( vec_x, vec_x0, sizeof(double)*nVar );

  diag_H = mxCalloc(nVar, sizeof(double));
  if( diag_H == NULL ) mexErrMsgTxt("Not enough memory.");
  for(i = 0; i < nVar; i++ ) 
    diag_H[i] = mat_H[nVar*i+i];
  

  /*------------------------------------------------------------------- */
  /* Call QP solver                                                     */
  /*------------------------------------------------------------------- */
  libqp_state_T state;
  state = libqp_gsmo_solver( &get_col, diag_H, f, a, b, LB, UB, vec_x, 
                        nVar, MaxIter, TolKKT, NULL );

  /*------------------------------------------------------------------- */
  /* Generate outputs                                                   */
  /*------------------------------------------------------------------- */

  plhs[1] = mxCreateDoubleScalar(state.QP);
  plhs[2] = mxCreateDoubleScalar((double)state.exitflag);
  plhs[3] = mxCreateDoubleScalar((double)state.nIter);


  /*------------------------------------------------------------------- */
  /* Clean up                                                           */
  /*------------------------------------------------------------------- */
  mxFree( diag_H );
}
コード例 #30
0
ファイル: cmex.c プロジェクト: AMFIRNAS/wso2-gridlabd
static CLASS *find_class(mxArray *handle)
{
	unsigned int64 *data = (unsigned int64*)mxGetPr(handle);
	return data[0]==MH_CLASS ? (CLASS*)data[1] : NULL;
}