void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *refs, *d, *out, *y, mu; int N, veclength; /* Check for proper number of arguments. */ if (nrhs != 4) mexErrMsgTxt("Four inputs required."); if (nlhs != 2) mexErrMsgTxt("Two outputs required."); /* Check to make sure the N input argument is a scalar. */ if (!mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || mxGetN(prhs[2])*mxGetM(prhs[2]) != 1) mexErrMsgTxt("Input N must be a scalar of type double."); /* Check to make sure the mu input argument is a scalar. */ if (!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) || mxGetN(prhs[3])*mxGetM(prhs[3]) != 1) mexErrMsgTxt("Input mu must be a scalar of type double."); /* Check that refs and d are doulbe */ if (!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) mexErrMsgTxt("Inputs must be of type double."); /* Check to make sure length refs and d is same and are col vectors. */ if (mxGetN(prhs[0]) != 1 || mxGetN(prhs[1]) != 1) mexErrMsgTxt("Reference and Input data must be column vectors."); if (mxGetM(prhs[0]) != mxGetM(prhs[1])) mexErrMsgTxt("Reference and Input must be of the same length."); /* Get inputs */ refs = mxGetPr(prhs[0]); d = mxGetPr(prhs[1]); N = (int) mxGetScalar(prhs[2]); mu = mxGetScalar(prhs[3]); /* Get the length of the inputs. */ veclength = mxGetM(prhs[0]); /* Create an mxArray for the output */ plhs[0] = mxCreateDoubleMatrix(veclength,1, mxREAL); plhs[1] = mxCreateDoubleMatrix(veclength,1, mxREAL); /* Set the output pointer to the output matrix. */ out = (double *) mxMalloc(veclength * sizeof(double)); y = (double *) mxMalloc(veclength * sizeof(double)); /* Call the C subroutine. */ fastranc(refs,d,N,mu,out,y,veclength); /* Assign the data array to the output array */ mxSetPr(plhs[0], out); mxSetPr(plhs[1], y); return; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *xin, *yin, *xout, *yout; size_t nin, nout; /* Check for proper number of arguments. */ if (nrhs!=2) mexErrMsgTxt("Two inputs required."); if (nlhs>2) mexErrMsgTxt("Too many output arguments."); /* Check for matching dimensions. */ if ( mxGetM(prhs[0]) != mxGetM(prhs[1]) || mxGetN(prhs[0]) != mxGetN(prhs[1]) ) mexErrMsgTxt("Inputs must have the same dimensions."); /* Check for proper numeric class and dimensions. */ if ( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( mxGetM(prhs[0]) != 1 && mxGetN(prhs[0]) != 1 ) ) mexErrMsgTxt("Inputs must be double non complex vectors."); /* Assign pointers to corresponding inputs. */ nin = mxGetNumberOfElements(prhs[0]); xin = mxGetPr(prhs[0]); yin = mxGetPr(prhs[1]); /* Call to triangulation function based on gpc. */ xout = NULL; yout = NULL; nout = 0; poly2tri_gpc(&xout, &yout, &nout, xin, yin, nin); /* Assign pointers to corresponding outputs. */ if (nlhs > 0) { plhs[0] = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL); mxSetM(plhs[0], 3); mxSetN(plhs[0], nout); mxSetPr(plhs[0], xout); } if (nlhs > 1) { plhs[1] = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL); mxSetM(plhs[1], 3); mxSetN(plhs[1], nout); mxSetPr(plhs[1], yout); } }
static double MatlabCallback(int n, const double *x, int *undefined_flag, void *data) { mxArray *rhs[2]; mxArray *lhs[2]; double *oldPtr; double fVal; bool violatesConstraints; //feval in Matlab will take the function handle and the state as //inputs. //The first function handle is f. rhs[0]=(mxArray*)data; rhs[1]=mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL); //Set the matrix data to x oldPtr=mxGetPr(rhs[1]); //x will not be modified, but the const must be typecast away to use //the mxSetPr function. mxSetPr(rhs[1],(double*)x); mxSetM(rhs[1], (size_t)n); mxSetN(rhs[1], 1); //Get the function value and gradient. mexCallMATLAB(2,lhs,2,rhs,"feval"); //Get the function value. fVal=getDoubleFromMatlab(lhs[0]); violatesConstraints=getBoolFromMatlab(lhs[1]); if(violatesConstraints) { *undefined_flag=1; } //Get rid of the returned Matlab Matrices. mxDestroyArray(lhs[0]); mxDestroyArray(lhs[1]); //Set the data pointer back to what it was during allocation that //mxDestroyArray does not have a problem. mxSetPr(rhs[1],oldPtr); mxSetM(rhs[1], 0); mxSetN(rhs[1], 0); //Get rid of the temporary natrix. mxDestroyArray(rhs[1]); return fVal; }
static int put_values ( Long nz, mxArray *A, double *Ax, // complex case: size 2*nz and freed on return, // real case: size nz, not freed on return. Long is_complex, cholmod_common *cc ) { Long imag_all_zero = TRUE ; if (is_complex) { // A is complex, stored in interleaved form; split it for MATLAB Long k ; double z, *Ax2, *Az2 ; mxFree (mxGetPi (A)) ; Ax2 = (double *) cholmod_l_malloc (nz, sizeof (double), cc) ; Az2 = (double *) cholmod_l_malloc (nz, sizeof (double), cc) ; for (k = 0 ; k < nz ; k++) { Ax2 [k] = Ax [2*k] ; z = Ax [2*k+1] ; if (z != 0) { imag_all_zero = FALSE ; } Az2 [k] = z ; } mxSetPr (A, Ax2) ; if (imag_all_zero) { // free the imaginary part, converting A to real cholmod_l_free (nz, sizeof (double), Az2, cc) ; Az2 = NULL ; } mxSetPi (A, Az2) ; // NOTE: the input Ax is freed cholmod_l_free (nz, sizeof (Complex), Ax, cc) ; } else { // A is real; just set Ax and return (do not free Ax) mxSetPr (A, Ax) ; } return (TRUE) ; }
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { if (nlhs > 1) { mexErrMsgTxt("Too many output arguments."); } switch(nrhs) { default: { mexErrMsgTxt("Incorrect number of arguments."); } case 0: { mexPrintf("\nColumnwise dot-product matrix with vector.\n\n"); break; } case 2: { int m=mxGetN(Vec); int n=mxGetN(Mat); Out=mxCreateDoubleMatrix(0,0,mxREAL); if (m == 1 && n > 0) { int i, j, k=0; const int* e=mxGetDimensions(Mat); double* or; double* inMat=mxGetPr(Mat); double* inVec=mxGetPr(Vec); mxSetDimensions(Out,e,2); mxSetPr(Out,or=(double*) mxMalloc(e[0]*e[1]*sizeof(double))); for (i=0; i<e[1]; i++) { for (j=0; j<e[0]; j++) { or[k] = inMat[k]*inVec[j]; k++; } } } } } }
/* return a complex sparse matrix to MATLAB */ mxArray *cs_cl_mex_put_sparse (cs_cl **Ahandle) { cs_cl *A ; double *x, *z ; mxArray *Amatlab ; CS_INT k ; A = *Ahandle ; if (!A) mexErrMsgTxt ("failed") ; Amatlab = mxCreateSparse (0, 0, 0, mxCOMPLEX) ; mxSetM (Amatlab, A->m) ; mxSetN (Amatlab, A->n) ; mxSetNzmax (Amatlab, A->nzmax) ; cs_cl_free (mxGetJc (Amatlab)) ; cs_cl_free (mxGetIr (Amatlab)) ; cs_cl_free (mxGetPr (Amatlab)) ; cs_cl_free (mxGetPi (Amatlab)) ; mxSetJc (Amatlab, (void *) (A->p)) ; /* assign A->p pointer to MATLAB A */ mxSetIr (Amatlab, (void *) (A->i)) ; x = cs_dl_malloc (A->nzmax, sizeof (double)) ; z = cs_dl_malloc (A->nzmax, sizeof (double)) ; for (k = 0 ; k < A->nzmax ; k++) { x [k] = creal (A->x [k]) ; /* copy and split numerical values */ z [k] = cimag (A->x [k]) ; } cs_cl_free (A->x) ; /* free copy of complex values */ mxSetPr (Amatlab, x) ; mxSetPi (Amatlab, z) ; cs_cl_free (A) ; /* frees A struct only, not A->p, etc */ *Ahandle = NULL ; return (Amatlab) ; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { //-- // DECLARE //-- double *x, *y, a, b; int x_nr_rows, x_nr_columns; double *mu, *var, *gamma; int m; //-- // HANDLE INPUT //-- /* GATEWAY */ if (nrhs!=4 || nlhs>1) mexErrMsgTxt("GGFIT: Supply arguments\nSyntax: Y = GENGG(X,SHAPE,DEV,MEAN)\n"); x_nr_rows = mxGetM(prhs[0]); x_nr_columns = mxGetN(prhs[0]); if (x_nr_rows >= x_nr_columns) { x_nr_columns = 1; } else { x_nr_rows = 1; } /* match inputs */ x = mxGetPr(prhs[0]); /* Complex parts ignored */ gamma = mxGetPr(prhs[1]); /* Complex parts ignored */ var = mxGetPr(prhs[2]); /* Complex parts ignored */ mu = mxGetPr(prhs[3]); /* Complex parts ignored */ /* match outputs */ y = mxCalloc(x_nr_rows*x_nr_columns,sizeof(double)); plhs[0] = mxCreateDoubleMatrix(x_nr_rows, x_nr_columns, mxREAL); mxSetM(plhs[0],x_nr_rows); mxSetN(plhs[0],x_nr_columns); mxSetPr(plhs[0],y); /* CALCULATION OF GENERALISED GAUSSIAN */ for (m=0; m<(x_nr_rows*x_nr_columns); m++) { b = pow( ( gammaHJB(3/(*gamma))/gammaHJB(1/(*gamma)) ),0.5 )/(*var); a = b*(*gamma)/(2*gammaHJB(1/(*gamma))); y[m] = a*exp( -pow( fabs(b*(x[m]- *mu)), *gamma ) ); } /* for */ } /* main */
int mfiles_cs2mx(const cs *in, mxArray *out) { if (!out) { return EXIT_FAILURE; } mxSetM(out, in->m); mxSetN(out, in->n); mxSetNzmax(out, in->nzmax); mxSetJc(out, (mwIndex *) in->p); mxSetIr(out, (mwIndex *) in->i); mxSetPr(out, in->x); return EXIT_SUCCESS; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *Cii ; double *ind_tr, *XYZv, weight, defl ; unsigned int mind, nind, mXYZv, nXYZv ; if (nrhs!=4) { mexErrMsgTxt("4 Inputs : ind_tri, XYZv, weight, defl") ; } else if (nlhs>1) { mexErrMsgTxt("1 Output : Cii_cog") ; } mind=mxGetM(prhs[0]) ; nind=mxGetN(prhs[0]) ; if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !(nind==3)) { mexErrMsgTxt("tri must be a matrix : Ntri x 3") ; } mXYZv=mxGetM(prhs[1]) ; nXYZv=mxGetN(prhs[1]) ; if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || (nXYZv!=3) ) { mexErrMsgTxt("X must be a matrix : Nvert x 3") ; } if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2]) || mxGetN(prhs[2])*mxGetM(prhs[2])!=1 ) { mexErrMsgTxt("weight must be a scalar") ; } if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsDouble(prhs[3]) || mxGetN(prhs[3])*mxGetM(prhs[3])!=1 ) { mexErrMsgTxt("defl must be a scalar") ; } plhs[0]=mxCreateDoubleMatrix(mind,mind,mxREAL) ; Cii=mxGetPr(plhs[0]) ; ind_tr=mxGetPr(prhs[0]) ; XYZv=mxGetPr(prhs[1]) ; weight = mxGetScalar(prhs[2]) ; defl = mxGetScalar(prhs[3]) ; Cii_cog(Cii, ind_tr, mind, XYZv, mXYZv, weight, defl) ; mxSetPr(plhs[0],Cii) ; }
mxArray *mxCreateNumericMatrixE(mwSize m, mwSize n, mxClassID classid, mxComplexity ComplexFlag) { mwSize sz = m*n*sizeof(double); mxArray *a = mxCreateNumericMatrix(1, 1, classid, ComplexFlag); mxSetM(a,m); mxSetN(a,n); mxSetPr(a, mxRealloc(mxGetPr(a),sz)); if(ComplexFlag == mxCOMPLEX) { mxSetPi(a, mxRealloc(mxGetPi(a),sz)); } return a; }
realtype *reAllocate2DOutputMemory( realtype *pMem, void *cvode_mem, N_Vector y0, mxArray *plhs, mwSize dim1, mwSize dim2 ) { void *pOld; pOld = pMem; pMem = mxRealloc( pMem, sizeof( realtype ) * dim1 * dim2 ); if ( pMem == NULL ) memErr( cvode_mem, y0, pOld, "ERROR: Insufficient memory for reallocation during simulation loop!" ); mxSetPr( plhs, pMem ); mxSetM( plhs, dim1 ); mxSetN( plhs, dim2 ); return pMem; }
static mxArray* AllocateOutputArray(const mxArray* In, int OutputChannels) { mxArray* Out = mxDuplicateArray(In); // Make a "deep copy" of Input array int nDimensions = mxGetNumberOfDimensions(In); const int* Dimensions = mxGetDimensions(In); int InputChannels = Dimensions[nDimensions-1]; // Modify pixel size only if needed if (InputChannels != OutputChannels) { int i, NewSize; int *ModifiedDimensions = (int*) mxMalloc(nDimensions * sizeof(int)); CopyMemory(ModifiedDimensions, Dimensions, nDimensions * sizeof(int)); ModifiedDimensions[nDimensions - 1] = OutputChannels; switch (mxGetClassID(In)) { case mxINT8_CLASS: NewSize = sizeof(char); break; case mxUINT8_CLASS: NewSize = sizeof(unsigned char); break; case mxINT16_CLASS: NewSize = sizeof(short); break; case mxUINT16_CLASS: NewSize = sizeof(unsigned short); break; default: case mxDOUBLE_CLASS: NewSize = sizeof(double); break; } // NewSize = 1; for (i=0; i < nDimensions; i++) NewSize *= ModifiedDimensions[i]; mxSetDimensions(Out, ModifiedDimensions, nDimensions); mxFree(ModifiedDimensions); mxSetPr(Out, mxRealloc(mxGetPr(Out), NewSize)); } return Out; }
/* return a real sparse matrix to MATLAB */ mxArray *cs_dl_mex_put_sparse (cs_dl **Ahandle) { cs_dl *A ; mxArray *Amatlab ; A = *Ahandle ; if (!A) mexErrMsgTxt ("failed") ; Amatlab = mxCreateSparse (0, 0, 0, mxREAL) ; mxSetM (Amatlab, A->m) ; mxSetN (Amatlab, A->n) ; mxSetNzmax (Amatlab, A->nzmax) ; cs_free (mxGetJc (Amatlab)) ; cs_free (mxGetIr (Amatlab)) ; cs_free (mxGetPr (Amatlab)) ; mxSetJc (Amatlab, (void *) (A->p)) ; /* assign A->p pointer to MATLAB A */ mxSetIr (Amatlab, (void *) (A->i)) ; mxSetPr (Amatlab, A->x) ; cs_free (A) ; /* frees A struct only, not A->p, etc */ *Ahandle = NULL ; return (Amatlab) ; }
mxArray *sfmult_yalloc // return Y ( Int m, Int n, int Ycomplex // true if Y is complex ) { // (TO DO): guard against integer overflow mxArray *Y = mxCreateDoubleMatrix (0, 0, Ycomplex ? mxCOMPLEX : mxREAL) ; MXFREE (mxGetPr (Y)) ; mxSetPr (Y, mxMalloc (MAX (m*n, 1) * sizeof (double))) ; if (Ycomplex) { MXFREE (mxGetPi (Y)) ; mxSetPi (Y, mxMalloc (MAX (m*n, 1) * sizeof (double))) ; } mxSetM (Y, m) ; mxSetN (Y, n) ; return (Y) ; }
void reset_nzmax(mxArray *spArray, const int old_nzmax, const int new_nzmax){ double *ptr; void *newptr; int *ir, *jc; int nbytes; if(new_nzmax == old_nzmax) return; nbytes = new_nzmax * sizeof(*ptr); ptr = mxGetPr(spArray); newptr = mxRealloc(ptr, nbytes); mxSetPr(spArray, newptr); nbytes = new_nzmax * sizeof(*ir); ir = mxGetIr(spArray); newptr = mxRealloc(ir, nbytes); mxSetIr(spArray, newptr); jc = mxGetJc(spArray); jc[0] = 0; jc[1] = new_nzmax; mxSetNzmax(spArray, new_nzmax); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int rows,cols,common,m,n,p; double y1, y2; double *arr1, *arr2, *arr3; if (nrhs!=2 || nlhs>1) mexErrMsgTxt("max_mult requires two inputs and one output"); if (mxIsChar(prhs[0]) || mxIsClass(prhs[0], "sparse") || mxIsComplex(prhs[0]) || mxIsChar(prhs[1]) || mxIsClass(prhs[1], "sparse") || mxIsComplex(prhs[1])) mexErrMsgTxt("Inputs must be real, full, and nonstring"); if (mxGetN(prhs[0])!=mxGetM(prhs[1])) mexErrMsgTxt("The number of columns of A must be the same as the number of rows of x"); arr1=mxGetPr(prhs[0]); arr2=mxGetPr(prhs[1]); p=mxGetN(prhs[0]); m=mxGetM(prhs[0]); n=mxGetN(prhs[1]); plhs[0]=mxCreateDoubleMatrix(m, n, mxREAL); arr3=mxMalloc(m*n*sizeof(double)); for (rows=0; rows<m ; rows++) for (cols=0; cols<n ; cols++) { y1=arr1[rows]*arr2[cols*p]; for (common=1; common<p; common++) { y2=arr1[rows+common*m]*arr2[common+cols*p]; if (y2>y1) y1=y2; } arr3[rows+cols*m]=y1; } mxSetPr(plhs[0], arr3); }
/* return a sparse matrix to MATLAB */ mxArray *cs_mex_put_sparse (cs **Ahandle) { cs *A ; mxArray *Amatlab ; A = *Ahandle ; Amatlab = mxCreateSparse (0, 0, 0, mxREAL) ; mxSetM (Amatlab, A->m) ; mxSetN (Amatlab, A->n) ; mxSetNzmax (Amatlab, A->nzmax) ; cs_free (mxGetJc (Amatlab)) ; cs_free (mxGetIr (Amatlab)) ; cs_free (mxGetPr (Amatlab)) ; mxSetJc (Amatlab, A->p) ; /* assign A->p pointer to MATLAB A */ mxSetIr (Amatlab, A->i) ; mxSetPr (Amatlab, A->x) ; mexMakeMemoryPersistent (A->p) ; /* ensure MATLAB does not free A->p */ mexMakeMemoryPersistent (A->i) ; mexMakeMemoryPersistent (A->x) ; cs_free (A) ; /* frees A struct only, not A->p, etc */ *Ahandle = NULL ; return (Amatlab) ; }
void SetColumnDoubleSparseMatrix(rMatrix plhs[], int element, int m, int n, double *mat, int column, double *arry, int *index, int size, int *nz) { int *jcs, *irs, i, ii, nzmax; double *sr, a; jcs = mxGetJc(plhs[element]); irs = mxGetIr(plhs[element]); sr = mxGetPr(plhs[element]); if (m > n) nzmax = m; else nzmax = n; if (nzmax < 10) nzmax = 10; jcs[column - 1] = *nz; for (i = 0; (i < size); i++) { a = arry[i]; if (a) { if (index == NULL) ii = i; else ii = index[i] - 1; if ((*nz != 0) && (((*nz) % nzmax) == 0)) { mxSetNzmax(plhs[element], *nz + nzmax); mxSetPr(plhs[element], matRealloc(sr, (*nz + nzmax) * sizeof(double))); mxSetIr(plhs[element], matRealloc(irs, (*nz + nzmax) * sizeof(int))); jcs = mxGetJc(plhs[element]); irs = mxGetIr(plhs[element]); sr = mxGetPr(plhs[element]); } sr[*nz] = a; irs[*nz] = ii; (*nz)++; } } jcs[column] = *nz; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *C ; double *XYZva, *ind_tra, *XYZvb, *ind_trb, weight, defl ; unsigned int mXYZva, nXYZva, minda, ninda ; unsigned int mXYZvb, nXYZvb, mindb, nindb ; if (nrhs!=6) { mexErrMsgTxt("6 Inputs : XYZva, ind_tra, XYZvb, ind_trb, weight, defl") ; } else if (nlhs>1) { mexErrMsgTxt("1 Outputs : Cij_cog") ; } mXYZva=mxGetM(prhs[0]) ; nXYZva=mxGetN(prhs[0]) ; if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || (nXYZva!=3)) { mexErrMsgTxt("XYZva must be a matrix : Nverta x 3") ; } minda=mxGetM(prhs[1]) ; ninda=mxGetN(prhs[1]) ; if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !(ninda==3)) { mexErrMsgTxt("ind_tra must be a matrix : Ntria x 3") ; } mXYZvb=mxGetM(prhs[2]) ; nXYZvb=mxGetN(prhs[2]) ; if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || (nXYZvb!=3)) { mexErrMsgTxt("XYZvb must be a matrix : Nvertb") ; } mindb=mxGetM(prhs[3]) ; nindb=mxGetN(prhs[3]) ; if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !(nindb==3)) { mexErrMsgTxt("ind_trb must be a matrix : Ntrib x 3") ; } if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4]) || !mxIsDouble(prhs[4]) || mxGetN(prhs[4])*mxGetM(prhs[4])!=1 ) { mexErrMsgTxt("weight must be a scalar") ; } if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5]) || mxIsSparse(prhs[5]) || !mxIsDouble(prhs[5]) || mxGetN(prhs[5])*mxGetM(prhs[5])!=1 ) { mexErrMsgTxt("defl must be a scalar") ; } plhs[0]=mxCreateDoubleMatrix(minda,mindb,mxREAL) ; C=mxGetPr(plhs[0]) ; XYZva=mxGetPr(prhs[0]) ; ind_tra=mxGetPr(prhs[1]) ; XYZvb=mxGetPr(prhs[2]) ; ind_trb=mxGetPr(prhs[3]) ; weight = mxGetScalar(prhs[4]) ; defl = mxGetScalar(prhs[5]) ; Cij(C,XYZva,mXYZva,ind_tra,minda, XYZvb,mXYZvb,ind_trb,mindb,weight,defl); mxSetPr(plhs[0],C) ; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *srwd, *srad, *MUZIN, *MUXIN, *theta, *phi, *thetad, *muz, *mux; double ALPHA,BETA; int W, J, D, A, MA = 0, NN, SEED, OUTPUT, nzmaxwd, nzmaxad, i, j, a, startcond; mwIndex *irwd, *jcwd, *irad, *jcad; /* Check for proper number of arguments. */ if (nrhs < 8) { mexErrMsgTxt("At least 8 input arguments required"); } else if (nlhs < 1) { mexErrMsgTxt("At least 1 output arguments required"); } startcond = 0; if (nrhs > 8) startcond = 1; /* dealing with sparse array WD */ if (mxIsDouble(prhs[0]) != 1) mexErrMsgTxt("WD must be a double precision matrix"); srwd = mxGetPr(prhs[0]); irwd = mxGetIr(prhs[0]); jcwd = mxGetJc(prhs[0]); nzmaxwd = (int) mxGetNzmax(prhs[0]); W = (int) mxGetM(prhs[0]); D = (int) mxGetN(prhs[0]); /* dealing with sparse array AD */ if (mxIsDouble(prhs[1]) != 1) mexErrMsgTxt("AD must be a double precision matrix"); srad = mxGetPr(prhs[1]); irad = mxGetIr(prhs[1]); jcad = mxGetJc(prhs[1]); nzmaxad = (int) mxGetNzmax(prhs[1]); A = (int) mxGetM(prhs[1]); if ((int) mxGetN(prhs[1]) != D) mexErrMsgTxt("WD and AD must have the same number of columns"); /* check that every document has some authors */ for (i=0; i<D; i++) { if ((jcad[i + 1] - jcad[i]) == 0) mexErrMsgTxt("there are some documents without authors in AD matrix "); if ((jcad[i + 1] - jcad[i]) > NAMAX) mexErrMsgTxt("Too many authors in some documents ... reached the NAMAX limit"); if ((jcad[i + 1] - jcad[i]) > MA) MA = (int) (jcad[i + 1] - jcad[i]); } phi = mxGetPr(prhs[2]); J = (int) mxGetM(prhs[2]); if (J<=0) mexErrMsgTxt("Number of topics must be greater than zero"); if ((int) mxGetN(prhs[2]) != W) mexErrMsgTxt("Vocabulary mismatches"); NN = (int) mxGetScalar(prhs[3]); if (NN<0) mexErrMsgTxt("Number of iterations must be greater than zero"); ALPHA = (double) mxGetScalar(prhs[4]); if (ALPHA<0) mexErrMsgTxt("ALPHA must be greater than zero"); BETA = (double) mxGetScalar(prhs[5]); if (BETA<0) mexErrMsgTxt("BETA must be greater than zero"); SEED = (int) mxGetScalar(prhs[6]); // set the seed of the random number generator OUTPUT = (int) mxGetScalar(prhs[7]); if (startcond == 1) { MUZIN = mxGetPr(prhs[8]); if (nzmaxwd != mxGetN(prhs[8])) mexErrMsgTxt("WD and MUZIN mismatch"); if (J != mxGetM( prhs[ 8 ])) mexErrMsgTxt("J and MUZIN mismatch"); MUXIN = mxGetPr(prhs[9]); if (nzmaxwd != mxGetN( prhs[9])) mexErrMsgTxt("WD and MUXIN mismatch"); if (MA != mxGetM(prhs[9])) mexErrMsgTxt("MA and MUXIN mismatch"); } // seeding seedMT( 1 + SEED * 2 ); // seeding only works on uneven numbers /* allocate memory */ muz = dvec(J*nzmaxwd); mux = dvec(MA*nzmaxwd); if (startcond == 1) { for (i=0; i<J*nzmaxwd; i++) muz[i] = (double) MUZIN[i]; for (a=0; a<MA*nzmaxwd; a++) mux[i] = (double) MUXIN[i]; } theta = dvec(J*A); /* run the model */ ATMBP( ALPHA, BETA, W, J, D, A, MA, NN, OUTPUT, irwd, jcwd, srwd, irad, jcad, muz, mux, phi, theta, startcond ); /* output */ plhs[0] = mxCreateDoubleMatrix(J, A, mxREAL); mxSetPr(plhs[0], theta); plhs[1] = mxCreateDoubleMatrix(J, nzmaxwd, mxREAL); mxSetPr(plhs[1], muz); plhs[2] = mxCreateDoubleMatrix(MA, nzmaxwd, mxREAL); mxSetPr(plhs[2], mux); }
/* ************************************************************ PROCEDURE mexFunction - Entry for Matlab ************************************************************ */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { jcir At, Ablk; mwIndex i,j, nblk,m, blknnz, njc, iwsize, blk0,blk1; mwIndex *iwork, *Ajc, *blkstart; const double *blkstartPr, *AjcPr; bool *cwork; bool isblk0negative; /* ------------------------------------------------------------ Check for proper number of arguments ------------------------------------------------------------ */ mxAssert(nrhs >= NPARIN, "findblks requires more input arguments."); mxAssert(nlhs <= NPAROUT, "findblks produces less output arguments."); /* -------------------------------------------------- GET inputs At, blkstart, Ablkjc, blk0, blk1 -------------------------------------------------- */ mxAssert(mxIsSparse(AT_IN), "At must be a sparse matrix."); At.jc = mxGetJc(AT_IN); At.ir = mxGetIr(AT_IN); m = mxGetN(AT_IN); nblk = mxGetM(BLKSTART_IN) * mxGetN(BLKSTART_IN) - 1; blkstartPr = mxGetPr(BLKSTART_IN); AjcPr = mxGetPr(ABLKJC_IN); mxAssert(m == mxGetM(ABLKJC_IN), "Ablkjc size mismatch."); njc = mxGetN(ABLKJC_IN); blk0 = (mwIndex) mxGetScalar(BLK0_IN); /* double to mwIndex */ isblk0negative=0; mxAssert(blk0>0,""); if(blk0>0) --blk0; /* Fortran to C */ else isblk0negative=1; if(mxGetM(BLK1_IN) * mxGetN(BLK1_IN) != 1) blk1 = njc; /*default to end */ else{ blk1 = (mwIndex) mxGetScalar(BLK1_IN); /* double to mwIndex (thus inf not allowed) */ mxAssert(blk1>0,""); --blk1; /* Fortran to C */ } /* ------------------------------------------------------------ Allocate working array iwork(nblk+2+log_2(1+nblk)), blkstart(2*nblk), Ajc(2*m) char cwork(nblk) ------------------------------------------------------------ */ iwsize = nblk + 2 + (mwIndex) floor(log(1.0+nblk)/log(2.0)); iwork = (mwIndex *) mxCalloc(iwsize, sizeof(mwIndex)); blkstart = (mwIndex *) mxCalloc(MAX(2*nblk,1), sizeof(mwIndex)); Ajc = (mwIndex *) mxCalloc(MAX(2*m,1), sizeof(mwIndex)); cwork = (bool *) mxCalloc(MAX(nblk,1), sizeof(bool)); /* ------------------------------------------------------------ Translate blkstart from Fortran-double to C-mwIndex ------------------------------------------------------------ */ for(i = 0; i < nblk; i++){ /* to integers */ j = (mwIndex) blkstartPr[i]; mxAssert(j>0,""); blkstart[i] = --j; mxAssert(j>0,""); blkstart[nblk+i] = --j; /* blkstart minus 1 */ } /* ------------------------------------------------------------ Convert Ajc from double to mwIndex: ------------------------------------------------------------ */ mxAssert(blk0 < njc, "Ablkjc size mismatches blk0."); if(isblk0negative) memcpy(Ajc,At.jc,m*sizeof(mwIndex)); /* default: start of column */ else for(i = 0; i < m; i++){ /* to integers */ Ajc[i] = (mwIndex) AjcPr[m*blk0 + i]; } mxAssert(blk1 >= 0, "blk1 must be positive."); if(blk1 >= njc) memcpy(Ajc+m,At.jc+1,m*sizeof(mwIndex)); /* default: end of column */ else for(i = 0; i < m; i++){ /* to integers */ Ajc[m+i] = (mwIndex) AjcPr[blk1*m + i]; } /* ------------------------------------------------------------ Ablk = sparse(nblk,m,blknnz); ------------------------------------------------------------ */ blknnz = 0; for(i = 0; i < m; i++) blknnz += Ajc[m+i]-Ajc[i]; /* upper bound on nnz blocks */ blknnz = MAX(blknnz,1); ABLK_OUT = mxCreateSparse(nblk,m, blknnz,mxREAL); Ablk.jc = mxGetJc(ABLK_OUT); Ablk.ir = mxGetIr(ABLK_OUT); /* ------------------------------------------------------------ The real job: ------------------------------------------------------------ */ findblks(Ablk.ir,Ablk.jc, Ajc,Ajc+m,At.ir, blkstart,blkstart+nblk, m,nblk, iwsize,cwork,iwork); /* ------------------------------------------------------------ REALLOC (shrink) Ablk to Ablk.jc[m] nonzeros. ------------------------------------------------------------ */ mxAssert(Ablk.jc[m] <= blknnz,""); blknnz = MAX(Ablk.jc[m],1); if((Ablk.ir = (mwIndex *) mxRealloc(Ablk.ir, blknnz * sizeof(mwIndex))) == NULL) mexErrMsgTxt("Memory allocation error"); if((Ablk.pr = (double *) mxRealloc(mxGetPr(ABLK_OUT), blknnz*sizeof(double))) == NULL) mexErrMsgTxt("Memory allocation error"); mxSetPr(ABLK_OUT,Ablk.pr); mxSetIr(ABLK_OUT,Ablk.ir); mxSetNzmax(ABLK_OUT,blknnz); for(i = 0; i < blknnz; i++) Ablk.pr[i] = 1.0; /* ------------------------------------------------------------ Release working arrays ------------------------------------------------------------ */ mxFree(cwork); mxFree(iwork); mxFree(Ajc); mxFree(blkstart); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* ---- findelemex will be called as : j_el=findelemex(xp,yp,AR,A,B,T); ---------------------------- */ /* ---- xp,yp are NOT nodal coordinates; they are the points we are finding elements for. Nodal coordinates have already been accounted for in A,B,T ----- */ int ip,j,np,nl,nh,ne; double *xp, *yp; double *AR,*A,*B,*T; double *fnd; double NaN=mxGetNaN(); double fac,S1,S2,S3,ONE,ZERO; double tol,*tolerance; /* ---- check I/O arguments ----------------------------------------- */ if (nrhs != 7) mexErrMsgTxt("findelemex requires 7 input arguments."); else if (nlhs != 1) mexErrMsgTxt("findelemex requires 1 output arguments."); /* ---- dereference input arrays ------------------------------------ */ xp =mxGetPr(prhs[0]); yp =mxGetPr(prhs[1]); AR =mxGetPr(prhs[2]); A =mxGetPr(prhs[3]); B =mxGetPr(prhs[4]); T =mxGetPr(prhs[5]); tolerance=mxGetPr(prhs[6]); tol=tolerance[0]; np=mxGetM(prhs[0]); ne=mxGetM(prhs[2]); /* ---- allocate space for list containing element numbers following NRC allocation style double *mxDvector(int nl,int nh) fnd= (double *) mxDvector(0,np); ---------------------------- */ fnd= (double *) mxDvector(0,np); for (ip=0;ip<np;ip++)fnd[ip]=-1.; ONE=1.+tol; ZERO=0.-tol; for (j=0;j<ne;j++){ for (ip=0;ip<np;ip++){ if(fnd[ip]<(double)0){ fac=.5/AR[j]; S1=(TT(j,0,ne)+BB(j,0,ne)*xp[ip]+AA(j,0,ne)*yp[ip])*fac; if (S1>ONE|S1<ZERO)goto l20; S2=(TT(j,1,ne)+BB(j,1,ne)*xp[ip]+AA(j,1,ne)*yp[ip])*fac; if (S2>ONE|S2<ZERO)goto l20; S3=(TT(j,2,ne)+BB(j,2,ne)*xp[ip]+AA(j,2,ne)*yp[ip])*fac; if (S3>ONE|S3<ZERO)goto l20; fnd[ip]=(double)(j+1); } l20: continue; } } for (ip=0;ip<np;ip++) if(fnd[ip]<(double)0)fnd[ip]=NaN; /* ---- Set elements of return matrix, pointed to by plhs[0] -------- */ plhs[0]=mxCreateDoubleMatrix(np,1,mxREAL); mxSetPr(plhs[0],fnd); /* ---- No need to free memory allocated with "mxCalloc"; MATLAB does this automatically. The CMEX allocation functions in "opnml_allocs.c" use mxCalloc. ----------------------------------- */ return; }
/* ************************************************************ PROCEDURE mexFunction - Entry for Matlab [lab,q] = eigK(x,K) Computes spectral coefficients of x w.r.t. K REMARK If this function is used internally by SeDuMi, then complex numbers are stored in a single real vector. To make it invokable from the Matlab command-line by the user, we also allow Matlab complex vector x. ************************************************************ */ void mexFunction(const int nlhs, mxArray *plhs[], const int nrhs, const mxArray *prhs[]) { mxArray *output_array[3], *Xk, *hXk; coneK cK; int k, nk, nksqr, lendiag,i,ii,nkp1, lenfull; double *lab,*q,*qpi,*labk,*xwork,*xpiwork; const double *x,*xpi; /* ------------------------------------------------------------ Check for proper number of arguments ------------------------------------------------------------ */ mxAssert(nrhs >= NPARIN, "eigK requires more input arguments"); mxAssert(nlhs <= NPAROUT, "eigK produces less output arguments"); /* ------------------------------------------------------------ Disassemble cone K structure ------------------------------------------------------------ */ conepars(K_IN, &cK); /* ------------------------------------------------------------ Compute statistics based on cone K structure ------------------------------------------------------------ */ lendiag = cK.lpN + 2 * (cK.lorN + cK.rconeN) + cK.rLen + cK.hLen; lenfull = cK.lpN + cK.qDim + cK.rDim + cK.hDim; if(cK.rconeN > 0) for(i = 0; i < cK.rconeN; i++) lenfull += cK.rconeNL[i]; /* ------------------------------------------------------------ Get input vector x ------------------------------------------------------------ */ mxAssert(mxGetM(X_IN) * mxGetN(X_IN) == lenfull, "Size mismatch x"); mxAssert(!mxIsSparse(X_IN), "x must be full (not sparse)."); x = mxGetPr(X_IN); if(mxIsComplex(X_IN)) xpi = mxGetPi(X_IN) + cK.lpN; /* ------------------------------------------------------------ Allocate output LAB(diag), eigvec Q(full for psd) ------------------------------------------------------------ */ LAB_OUT = mxCreateDoubleMatrix(lendiag, 1, mxREAL); lab = mxGetPr(LAB_OUT); if(nlhs > 1){ if(mxIsComplex(X_IN)){ Q_OUT = mxCreateDoubleMatrix(cK.rDim, 1, mxCOMPLEX); qpi = mxGetPi(Q_OUT); } else Q_OUT = mxCreateDoubleMatrix(cK.rDim + cK.hDim, 1, mxREAL); q = mxGetPr(Q_OUT); } /* ------------------------------------------------------------ Allocate working arrays: ------------------------------------------------------------ */ Xk = mxCreateDoubleMatrix(0,0,mxREAL); hXk = mxCreateDoubleMatrix(0,0,mxCOMPLEX); if(mxIsComplex(X_IN)){ xwork = (double *) mxCalloc(MAX(1,2 * SQR(cK.rMaxn)), sizeof(double)); xpiwork = xwork + SQR(cK.rMaxn); } else xwork =(double *) mxCalloc(MAX(1,SQR(cK.rMaxn)+2*SQR(cK.hMaxn)), sizeof(double)); /* ------------------------------------------------------------ The actual job is done here:. ------------------------------------------------------------ */ if(cK.lpN){ /* ------------------------------------------------------------ LP: lab = x ------------------------------------------------------------ */ memcpy(lab, x, cK.lpN * sizeof(double)); lab += cK.lpN; x += cK.lpN; } /* ------------------------------------------------------------ CONSIDER FIRST MATLAB-REAL-TYPE: ------------------------------------------------------------ */ if(!mxIsComplex(X_IN)){ /* Not Matlab-type complex */ /* ------------------------------------------------------------ LORENTZ: (I) lab = qeig(x) ------------------------------------------------------------ */ for(k = 0; k < cK.lorN; k++){ nk = cK.lorNL[k]; qeig(lab,x,nk); lab += 2; x += nk; } /* ------------------------------------------------------------ RCONE: LAB = eig(X) (Lorentz-Rcone's are not used internally) ------------------------------------------------------------ */ for(k = 0; k < cK.rconeN; k++){ nk = cK.rconeNL[k]; rconeeig(lab,x[0],x[1],realssqr(x+2,nk-2)); lab += 2; x += nk; } /* ------------------------------------------------------------ PSD: (I) LAB = eig(X) ------------------------------------------------------------ */ if(nlhs < 2){ for(k=0; k < cK.rsdpN; k++){ /* real symmetric */ nk = cK.sdpNL[k]; symproj(xwork,x,nk); /* make it symmetric */ mxSetM(Xk, nk); mxSetN(Xk, nk); mxSetPr(Xk, xwork); mexCallMATLAB(1, output_array, 1, &Xk, "eig"); memcpy(lab, mxGetPr(output_array[0]), nk * sizeof(double)); /* ------------------------------------------------------------ With mexCallMATLAB, we invoked the mexFunction "eig", which allocates a matrix struct *output_array[0], AND a block for the float data of that matrix. ==> mxDestroyArray() does not only free the float data, it also releases the matrix struct (and this is what we want). ------------------------------------------------------------ */ mxDestroyArray(output_array[0]); lab += nk; x += SQR(nk); } /* ------------------------------------------------------------ WARNING: Matlab's eig doesn't recognize Hermitian, hence VERY slow ------------------------------------------------------------ */ for(; k < cK.sdpN; k++){ /* complex Hermitian */ nk = cK.sdpNL[k]; nksqr = SQR(nk); symproj(xwork,x,nk); /* make it Hermitian */ skewproj(xwork + nksqr,x+nksqr,nk); mxSetM(hXk, nk); mxSetN(hXk, nk); mxSetPr(hXk, xwork); mxSetPi(hXk, xwork + nksqr); mexCallMATLAB(1, output_array, 1, &hXk, "eig"); memcpy(lab, mxGetPr(output_array[0]), nk * sizeof(double)); mxDestroyArray(output_array[0]); lab += nk; x += 2 * nksqr; } } else{ /* ------------------------------------------------------------ SDP: (II) (Q,LAB) = eig(X) ------------------------------------------------------------ */ for(k=0; k < cK.rsdpN; k++){ /* real symmetric */ nk = cK.sdpNL[k]; symproj(xwork,x,nk); /* make it symmetric */ mxSetM(Xk, nk); mxSetN(Xk, nk); mxSetPr(Xk, xwork); mexCallMATLAB(2, output_array, 1, &Xk, "eig"); nksqr = SQR(nk); /* copy Q-matrix */ memcpy(q, mxGetPr(output_array[0]), nksqr * sizeof(double)); nkp1 = nk + 1; /* copy diag(Lab) */ labk = mxGetPr(output_array[1]); for(i = 0, ii = 0; i < nk; i++, ii += nkp1) lab[i] = labk[ii]; mxDestroyArray(output_array[0]); mxDestroyArray(output_array[1]); lab += nk; x += nksqr; q += nksqr; } for(; k < cK.sdpN; k++){ /* complex Hermitian */ nk = cK.sdpNL[k]; nksqr = SQR(nk); symproj(xwork,x,nk); /* make it Hermitian */ skewproj(xwork + nksqr,x+nksqr,nk); mxSetM(hXk, nk); mxSetN(hXk, nk); mxSetPr(hXk, xwork); mxSetPi(hXk, xwork+nksqr); mexCallMATLAB(2, output_array, 1, &hXk, "eig"); memcpy(q, mxGetPr(output_array[0]), nksqr * sizeof(double)); q += nksqr; if(mxIsComplex(output_array[0])) /* if any imaginary part */ memcpy(q, mxGetPi(output_array[0]), nksqr * sizeof(double)); nkp1 = nk + 1; /* copy diag(Lab) */ labk = mxGetPr(output_array[1]); for(i = 0, ii = 0; i < nk; i++, ii += nkp1) lab[i] = labk[ii]; mxDestroyArray(output_array[0]); mxDestroyArray(output_array[1]); lab += nk; x += 2 * nksqr; q += nksqr; } } /* [lab,q] = eigK */ } /* !iscomplex */ else{ /* is MATLAB type complex */ /* ------------------------------------------------------------ LORENTZ: (I) lab = qeig(x) ------------------------------------------------------------ */ for(k = 0; k < cK.lorN; k++){ nk = cK.lorNL[k]; cxqeig(lab,x,xpi,nk); lab += 2; x += nk; xpi += nk; } /* ------------------------------------------------------------ RCONE: LAB = eig(X) (Lorentz-Rcone's are not used internally) ------------------------------------------------------------ */ for(k = 0; k < cK.rconeN; k++){ nk = cK.rconeNL[k]; rconeeig(lab,x[0],x[1], realssqr(x+2,nk-2) + realssqr(xpi+2,nk-2)); lab += 2; x += nk; xpi += nk; } /* ------------------------------------------------------------ PSD: (I) LAB = eig(X) ------------------------------------------------------------ */ for(k = 0; k < cK.sdpN; k++){ nk = cK.sdpNL[k]; nksqr = SQR(nk); symproj(xwork,x,nk); /* make it Hermitian */ skewproj(xpiwork,xpi,nk); mxSetM(hXk, nk); mxSetN(hXk, nk); mxSetPr(hXk, xwork); mxSetPi(hXk, xpiwork); if(nlhs < 2){ mexCallMATLAB(1, output_array, 1, &hXk, "eig"); memcpy(lab, mxGetPr(output_array[0]), nk * sizeof(double)); } else{ mexCallMATLAB(2, output_array, 1, &hXk, "eig"); memcpy(q, mxGetPr(output_array[0]), nksqr * sizeof(double)); if(mxIsComplex(output_array[0])) /* if any imaginary part */ memcpy(qpi, mxGetPi(output_array[0]), nksqr * sizeof(double)); nkp1 = nk + 1; /* copy diag(Lab) */ labk = mxGetPr(output_array[1]); for(i = 0, ii = 0; i < nk; i++, ii += nkp1) lab[i] = labk[ii]; mxDestroyArray(output_array[1]); q += nksqr; qpi += nksqr; } mxDestroyArray(output_array[0]); lab += nk; x += nksqr; xpi += nksqr; } } /* iscomplex */ /* ------------------------------------------------------------ Release PSD-working arrays. ------------------------------------------------------------ */ mxSetM(Xk,0); mxSetN(Xk,0); mxSetPr(Xk, (double *) NULL); mxDestroyArray(Xk); mxSetM(hXk,0); mxSetN(hXk,0); mxSetPr(hXk, (double *) NULL); mxSetPi(hXk, (double *) NULL); mxDestroyArray(hXk); mxFree(xwork); }
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double t1, t2; double *G, *P, *H2jj, *H2kk; int i, j, k, nbasis; mxArray *H2j, *H2k, *mH2jj, *mH2kk; if (nlhs > 1) mexErrMsgIdAndTxt("twoElecFock:nlhs", "Invalid number of output variables for twoElecFock."); if (nrhs != 3) mexErrMsgIdAndTxt("twoElecFock:nrhs", "Invalid number of input variables to twoElecFock."); /* Pull data out of the input arrays. */ P = mxGetPr(prhs[0]); H2j = (mxArray*)prhs[1]; H2k = (mxArray*)prhs[2]; nbasis = (int)mxGetM(prhs[0]); /* Validate input. */ CHECK(nbasis == mxGetM(prhs[0])); CHECK(nbasis == mxGetN(prhs[0])); CHECK(nbasis == mxGetM(H2j)); CHECK(nbasis == mxGetN(H2j)); CHECK(nbasis == mxGetM(H2k)); CHECK(nbasis == mxGetN(H2k)); /* Allocate the return array. */ G = mxCalloc(nbasis * nbasis, sizeof(double)); /* * Theoretically, this order of loop variables is the most cache efficient, * but testing doesn't show any appreciable difference in practice. */ for (j = 0; j < nbasis; j++) { for (i = j; i < nbasis; i++) { t1 = 0.0; t2 = 0.0; /* Get current arrrays out of the cell arrays and validate input. */ mH2jj = mxGetCell(H2j, CMO2(i, j, nbasis)); mH2kk = mxGetCell(H2k, CMO2(i, j, nbasis)); CHECK(nbasis == mxGetM(mH2jj)); CHECK(nbasis == mxGetN(mH2jj)); CHECK(nbasis == mxGetM(mH2kk)); CHECK(nbasis == mxGetN(mH2kk)); H2jj = mxGetPr(mH2jj); H2kk = mxGetPr(mH2kk); /* Build the elements of G. */ for (k = 0; k < nbasis * nbasis; k++) { t1 += H2jj[k] * P[k]; t2 += H2kk[k] * P[k]; } G[CMO2(i, j, nbasis)] = t1 - t2 / 2; /* Taking advantage of symmetry. */ if (i != j) G[CMO2(j, i, nbasis)] = t1 - t2 / 2; } } /* Prepare the data to hand back to MATLAB. */ plhs[0] = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL); mxSetPr(plhs[0], G); mxSetM(plhs[0], nbasis); mxSetN(plhs[0], nbasis); return; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { const mxArray *MatlabFunctionHandle; direct_algorithm theAlgorithm=DIRECT_ORIGINAL; const direct_objective_func f=&MatlabCallback; size_t numDim; double *lowerBounds; double *upperBounds; int maxFEval=500; int maxIter=100; double epsilon=1e-4; double epsilonAbs=0; double volumeRelTol=1e-10; double sigmaRelTol=0; double fGlobal=DIRECT_UNKNOWN_FGLOBAL; double fGlobalRelTol=DIRECT_UNKNOWN_FGLOBAL; int maxDiv=5000; //To hold return values direct_return_code retVal; double *x; double fVal; if(nrhs<3||nrhs>4){ mexErrMsgTxt("Wrong number of inputs"); } if(nlhs>3) { mexErrMsgTxt("Wrong number of outputs."); } //Check that a function handle was passed. if(!mxIsClass(prhs[0],"function_handle")) { mexErrMsgTxt("The first input must be a function handle."); } MatlabFunctionHandle=prhs[0]; //Check the lower and upper bounds checkRealDoubleArray(prhs[1]); checkRealDoubleArray(prhs[2]); numDim=mxGetM(prhs[1]); if(numDim<1||mxGetN(prhs[1])!=1) { mexErrMsgTxt("The lower bounds have the wrong dimensionality."); } if(mxGetM(prhs[2])!=numDim||mxGetN(prhs[1])!=1) { mexErrMsgTxt("The upper bounds have the wrong dimensionality."); } //The function in the library only uses integers for dimensions. if(numDim>INT_MAX) { mexErrMsgTxt("The problem has too many dimensions to be solved using this function."); } lowerBounds=(double*)mxGetData(prhs[1]); upperBounds=(double*)mxGetData(prhs[2]); //If a structure of options was given if(nrhs>3&&!mxIsEmpty(prhs[3])) { //We have to check for every possible structure member. mxArray *theField; if(!mxIsStruct(prhs[3])) { mexErrMsgTxt("The options must be given in a structure."); } theField=mxGetField(prhs[3],0,"algorithm"); if(theField!=NULL) {//If the field is present. int algType=getIntFromMatlab(theField); //Algorithm type switch(algType) { case 0: theAlgorithm=DIRECT_ORIGINAL; break; case 1: theAlgorithm=DIRECT_GABLONSKY; break; default: mexErrMsgTxt("Invalid algorithm specified"); } } theField=mxGetField(prhs[3],0,"maxDiv"); if(theField!=NULL) {//If the field is present. maxDiv=getIntFromMatlab(theField); if(maxDiv<1) { mexErrMsgTxt("Invalid maxDiv specified"); } } theField=mxGetField(prhs[3],0,"maxIter"); if(theField!=NULL) {//If the field is present. maxIter=getIntFromMatlab(theField); if(maxIter<1) { mexErrMsgTxt("Invalid maxIter specified"); } } theField=mxGetField(prhs[3],0,"maxFEval"); if(theField!=NULL) {//If the field is present. maxFEval=getIntFromMatlab(theField); if(maxIter<1) { mexErrMsgTxt("Invalid maxFEval specified"); } } theField=mxGetField(prhs[3],0,"epsilon"); if(theField!=NULL) {//If the field is present. epsilon=getDoubleFromMatlab(theField); if(fabs(epsilon)>=1) { mexErrMsgTxt("Invalid epsilon specified"); } } theField=mxGetField(prhs[3],0,"epsilonAbs"); if(theField!=NULL) {//If the field is present. epsilonAbs=getDoubleFromMatlab(theField); if(epsilonAbs>=1||epsilonAbs<0) { mexErrMsgTxt("Invalid epsilonAbs specified"); } } theField=mxGetField(prhs[3],0,"volumeRelTol"); if(theField!=NULL) {//If the field is present. volumeRelTol=getDoubleFromMatlab(theField); if(volumeRelTol>=1||volumeRelTol<0) { mexErrMsgTxt("Invalid volumeRelTol specified"); } } theField=mxGetField(prhs[3],0,"sigmaRelTol"); if(theField!=NULL) {//If the field is present. sigmaRelTol=getDoubleFromMatlab(theField); if(sigmaRelTol>=1||sigmaRelTol<0) { mexErrMsgTxt("Invalid sigmaRelTol specified"); } } theField=mxGetField(prhs[3],0,"fGlobal"); if(theField!=NULL) {//If the field is present. fGlobal=getDoubleFromMatlab(theField); fGlobalRelTol=1e-12;//Default value if fGlobal is given. } theField=mxGetField(prhs[3],0,"fGlobalRelTol"); if(theField!=NULL) {//If the field is present. fGlobalRelTol=getDoubleFromMatlab(theField); if(fGlobalRelTol<0) { mexErrMsgTxt("Invalid fGlobalRelTol specified"); } } } //Allocate space for the return values x=mxCalloc(numDim, sizeof(double)); retVal=direct_optimize(f,//Objective function pointer (void*)MatlabFunctionHandle,//Data that passed to the objective function. Here, the function handle passed by the user. (int)numDim,//The dimensionality of the problem lowerBounds,//Array of the lower bound of each dimension. upperBounds,//Array of the upper bound of each dimension. x,//An array that will be set to the optimum value on return. &fVal,//On return, set to the minimum value. maxFEval,//Maximum number of function evaluations. maxIter,//Maximum number of iterations epsilon,//Jones' epsilon parameter (1e-4 is recommended) epsilonAbs,//An absolute version of magic_eps //Relative tolerance on the hypercube volume (use 0 if none). This is //a percentage (0-1) of the volume of the original hypercube volumeRelTol, //Relative tolerance on the hypercube measure (0 if none) sigmaRelTol, //A pointer to a variable that can terminate the optimization. This is //in the library's code so that an external thread can write to this //and force the optimization to stop. Here, we are not using it, so we //can pass NULL. NULL, fGlobal,//Function value of the global optimum, if known. Use DIRECT_UNKNOWN_FGLOBAL if unknown. fGlobalRelTol,//Relative tolerance for convergence if fglobal is known. If unknown, use DIRECT_UNKNOWN_FGLOBAL. NULL,//There is no output to a file. theAlgorithm,//The algorithm to use maxDiv);//The maximum number of hyperrectangle divisions //If an error occurred if(retVal<0) { mxFree(x); switch(retVal){ case DIRECT_INVALID_BOUNDS: mexErrMsgTxt("Upper bounds are <= lower bounds for one or more dimensions."); case DIRECT_MAXFEVAL_TOOBIG: mexErrMsgTxt("maxFEval is too large."); case DIRECT_INIT_FAILED: mexErrMsgTxt("An initialization step failed."); case DIRECT_SAMPLEPOINTS_FAILED: mexErrMsgTxt("An error occurred creating sampling points."); case DIRECT_SAMPLE_FAILED: mexErrMsgTxt("An error occurred while sampling the function."); case DIRECT_OUT_OF_MEMORY: mexErrMsgTxt("Out of memory"); case DIRECT_INVALID_ARGS: mexErrMsgTxt("Invalid arguments provided"); //These errors should not occur either because they should //never be called or because retVal>=0 so these are not //actually errors. case DIRECT_FORCED_STOP: case DIRECT_MAXFEVAL_EXCEEDED: case DIRECT_MAXITER_EXCEEDED: case DIRECT_GLOBAL_FOUND: case DIRECT_VOLTOL: case DIRECT_SIGMATOL: case DIRECT_MAXTIME_EXCEEDED: default: mexErrMsgTxt("An unknown error occurred."); } } //Set the return values plhs[0]=mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL); mxFree(mxGetPr(plhs[0])); mxSetPr(plhs[0], x); mxSetM(plhs[0], numDim); mxSetN(plhs[0], 1); if(nlhs>1) { plhs[1]=doubleMat2Matlab(&fVal,1,1); if(nlhs>2) { plhs[2]=intMat2MatlabDoubles(&retVal,1,1); } } }
void utility::stdVector2matlabVector(vector<double> *input, mxArray *outputMatrix) { outputMatrix = mxCreateDoubleMatrix(input->size(), 1, mxREAL); mxSetPr(outputMatrix, &(input->at(0))); }
/* ---------------------------------------------------------------------------------- */ int conditional_xyz ( mxArray *plhs[], LASreader *reader, LASheader *header, double ang, int classif, int intens, int nRet, int srcID, int got_R, double west, double east, double south, double north, double z_min, double z_max) { /* Get the XYZ triplets that escape excluding clausules */ unsigned int n = 0, n_alloc = 100000; int got_Z = FALSE, first_only, last_only; double *ptr, *tmp, x, y, z, MinZ, MaxZ; last_only = (nRet > 9 ) ? TRUE : FALSE; first_only = (nRet == 1 ) ? TRUE : FALSE; if (z_min > -1000) { got_Z = TRUE; MinZ = header->min_z; MaxZ = header->max_z; } ptr = (double *)mxMalloc((mwSize)(n_alloc * 3 * sizeof(double))); while (reader->read_point()) { if (classif && reader->point.classification != classif) goto fim; if (srcID && reader->point.point_source_ID != srcID) goto fim; if (intens && reader->point.intensity < intens) goto fim; if (last_only && reader->point.return_number != reader->point.number_of_returns_of_given_pulse) goto fim; if (first_only && reader->point.return_number != 1) goto fim; if (ang && (reader->point.scan_angle_rank > ang || reader->point.scan_angle_rank < -ang)) goto fim; x = reader->point.get_x(); y = reader->point.get_y(); if (got_R && (x < west || x > east || y < south || y > north)) goto fim; z = reader->point.get_z(); if (got_Z && (z < MinZ || z > MaxZ)) goto fim; ptr[n*3] = x; ptr[n*3+1] = y; ptr[n*3+2] = z; n++; if (n >= n_alloc) { n_alloc += 50000; ptr = (double *)mxRealloc((void *)ptr, (mwSize)(n_alloc * 3 * sizeof(double))); } fim: ; } if (n) { n--; ptr = (double *)mxRealloc((void *)ptr, (mwSize)(n * 3 * sizeof(double))); plhs[0] = mxCreateDoubleMatrix(3, 1, mxREAL); tmp = mxGetPr(plhs[0]); mxFree((void *)tmp); mxSetPr(plhs[0], ptr); mxSetN(plhs[0], (mwSize)n); } else plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL); /* We got no points */ return (n); }
/* ************************************************************ PROCEDURE mexFunction - Entry for Matlab ************************************************************ */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { const mxArray *L_FIELD; mwIndex maxnnz, i,j, nsuper,m,n; const mwIndex *ljc,*lir,*bjc,*bir; mwIndex *xjc,*xir, *snode,*xlindx,*lindx, *iwork,*xsuper, *invperm; bool *cwork; double *xpr; const double *permPr, *xsuperPr; /* ------------------------------------------------------------ Check for proper number of arguments ------------------------------------------------------------ */ mxAssert(nrhs >= NPARIN, "symbfwblk requires more input arguments"); mxAssert(nlhs <= NPAROUT, "symbfwblk produces 1 output argument"); /* ------------------------------------------------------------ Get rhs-input B ------------------------------------------------------------ */ mxAssert(mxIsSparse(B_IN), "B must be sparse"); m = mxGetM(B_IN); n = mxGetN(B_IN); bjc = mxGetJc(B_IN); bir = mxGetIr(B_IN); /* ------------------------------------------------------------ Disassemble block Cholesky structure L ------------------------------------------------------------ */ mxAssert(mxIsStruct(L_IN), "Parameter `L' should be a structure."); L_FIELD = mxGetField(L_IN,(mwIndex)0,"perm"); mxAssert( L_FIELD != NULL, "Missing field L.perm."); /* L.perm */ mxAssert(m == mxGetM(L_FIELD) * mxGetN(L_FIELD), "L.perm size mismatches B"); permPr = mxGetPr(L_FIELD); L_FIELD = mxGetField(L_IN,(mwIndex)0,"L"); mxAssert( L_FIELD!= NULL, "Missing field L.L."); /* L.L */ mxAssert( m == mxGetM(L_FIELD) && m == mxGetN(L_FIELD), "Size L.L mismatch."); mxAssert(mxIsSparse(L_FIELD), "L.L should be sparse."); ljc = mxGetJc(L_FIELD); lir = mxGetIr(L_FIELD); L_FIELD = mxGetField(L_IN,(mwIndex)0,"xsuper"); mxAssert( L_FIELD!= NULL, "Missing field L.xsuper."); /* L.xsuper */ nsuper = mxGetM(L_FIELD) * mxGetN(L_FIELD) - 1; mxAssert( nsuper <= m , "Size L.xsuper mismatch."); xsuperPr = mxGetPr(L_FIELD); /* ------------------------------------------------------------ Allocate mwIndex-part of sparse output matrix X(m x n) Heuristically set nnz to nnz(B) + 4*m. ------------------------------------------------------------ */ maxnnz = bjc[n] + 4 * m; xjc = (mwIndex *) mxCalloc(n + 1, sizeof(mwIndex)); xir = (mwIndex *) mxCalloc(maxnnz, sizeof(mwIndex)); /* ------------------------------------------------------------ Allocate working arrays: mwIndex invperm(m), snode(m), xsuper(nsuper+1), xlindx(nsuper+1), lindx(nnz(L)), iwork(nsuper). char cwork(nsuper). ------------------------------------------------------------ */ invperm = (mwIndex *) mxCalloc(m,sizeof(mwIndex)); snode = (mwIndex *) mxCalloc(m,sizeof(mwIndex)); xsuper = (mwIndex *) mxCalloc(nsuper+1,sizeof(mwIndex)); xlindx = (mwIndex *) mxCalloc(nsuper+1,sizeof(mwIndex)); lindx = (mwIndex *) mxCalloc(ljc[m], sizeof(mwIndex)); iwork = (mwIndex *) mxCalloc(nsuper, sizeof(mwIndex)); cwork = (bool *) mxCalloc(nsuper, sizeof(bool)); /* ------------------------------------------------------------ Convert PERM, XSUPER to integer and C-Style ------------------------------------------------------------ */ for(i = 0; i < m; i++){ j = (mwIndex) permPr[i]; mxAssert(j>0,""); invperm[--j] = i; /* so that invperm[perm[i]] = i */ } for(i = 0; i <= nsuper; i++){ j = (mwIndex) xsuperPr[i]; mxAssert(j>0,""); xsuper[i] = --j; } /* ------------------------------------------------------------ Create "snode" from xsuper, and get compact subscript (xlindx,lindx) from (ljc,lir,xsuper), i.e. nz-pattern per supernode. ------------------------------------------------------------ */ snodeCompress(xlindx,lindx,snode, ljc,lir,xsuper,nsuper); /* ------------------------------------------------------------ Compute nz structure after forward solve ------------------------------------------------------------ */ symbfwmat(xjc, &xir, &maxnnz, bjc, bir, invperm, snode, xsuper, xlindx, lindx, nsuper, m, n, iwork, cwork); /* ------------------------------------------------------------ Create output matrix x ------------------------------------------------------------ */ X_OUT = mxCreateSparse(m,n, (mwSize)1,mxREAL); mxFree(mxGetJc(X_OUT)); /* jc */ mxFree(mxGetIr(X_OUT)); /* ir */ mxFree(mxGetPr(X_OUT)); /* pr */ xpr = (double *) mxCalloc(maxnnz,sizeof(double)); mxSetJc(X_OUT, xjc); mxSetIr(X_OUT, xir); mxSetPr(X_OUT, xpr); mxSetNzmax(X_OUT, maxnnz); for(i = 0; i < maxnnz; i++) xpr[i] = 1.0; /* ------------------------------------------------------------ Release working arrays. ------------------------------------------------------------ */ mxFree(cwork); mxFree(iwork); mxFree(lindx); mxFree(xlindx); mxFree(xsuper); mxFree(snode); mxFree(invperm); }
mxArray *ssmult_transpose // returns C = A' or A.' ( const mxArray *A, int conj // compute A' if true, compute A.' if false ) { Int *Cp, *Ci, *Ap, *Ai, *W ; double *Cx, *Cz, *Ax, *Az ; // (TO DO): do single too mxArray *C ; Int p, pend, q, i, j, n, m, anz, cnz ; int C_is_complex ; //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- m = mxGetM (A) ; n = mxGetN (A) ; Ap = mxGetJc (A) ; Ai = mxGetIr (A) ; Ax = mxGetPr (A) ; Az = mxGetPi (A) ; anz = Ap [n] ; C_is_complex = mxIsComplex (A) ; //-------------------------------------------------------------------------- // allocate C but do not initialize it //-------------------------------------------------------------------------- cnz = MAX (anz, 1) ; C = mxCreateSparse (0, 0, 0, C_is_complex ? mxCOMPLEX : mxREAL) ; MXFREE (mxGetJc (C)) ; MXFREE (mxGetIr (C)) ; MXFREE (mxGetPr (C)) ; MXFREE (mxGetPi (C)) ; Cp = mxMalloc ((m+1) * sizeof (Int)) ; Ci = mxMalloc (MAX (cnz,1) * sizeof (Int)) ; Cx = mxMalloc (MAX (cnz,1) * sizeof (double)) ; Cz = C_is_complex ? mxMalloc (MAX (cnz,1) * sizeof (double)) : NULL ; mxSetJc (C, Cp) ; mxSetIr (C, Ci) ; mxSetPr (C, Cx) ; mxSetPi (C, Cz) ; mxSetNzmax (C, cnz) ; mxSetM (C, n) ; mxSetN (C, m) ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- W = mxCalloc (MAX (m,1), sizeof (Int)) ; //-------------------------------------------------------------------------- // compute row counts //-------------------------------------------------------------------------- for (p = 0 ; p < anz ; p++) { W [Ai [p]]++ ; } //-------------------------------------------------------------------------- // compute column pointers of C and copy back into W //-------------------------------------------------------------------------- for (p = 0, i = 0 ; i < m ; i++) { Cp [i] = p ; p += W [i] ; W [i] = Cp [i] ; } Cp [m] = p ; //-------------------------------------------------------------------------- // C = A' //-------------------------------------------------------------------------- p = 0 ; if (!C_is_complex) { // C = A' (real case) for (j = 0 ; j < n ; j++) { pend = Ap [j+1] ; for ( ; p < pend ; p++) { q = W [Ai [p]]++ ; // find position for C(j,i) Ci [q] = j ; // place A(i,j) as entry C(j,i) Cx [q] = Ax [p] ; } } } else if (conj) { // C = A' (complex conjugate) for (j = 0 ; j < n ; j++) { pend = Ap [j+1] ; for ( ; p < pend ; p++) { q = W [Ai [p]]++ ; // find position for C(j,i) Ci [q] = j ; // place A(i,j) as entry C(j,i) Cx [q] = Ax [p] ; Cz [q] = -Az [p] ; } } } else { // C = A.' (complex case) for (j = 0 ; j < n ; j++) { pend = Ap [j+1] ; for ( ; p < pend ; p++) { q = W [Ai [p]]++ ; // find position for C(j,i) Ci [q] = j ; // place A(i,j) as entry C(j,i) Cx [q] = Ax [p] ; Cz [q] = Az [p] ; } } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- MXFREE (W) ; return (C) ; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ //setting up inputs //first, set up the structs const mxArray* data = mxDuplicateArray(prhs[0]); const mxArray* model = mxDuplicateArray(prhs[1]); const mxArray* samp = mxDuplicateArray(prhs[2]); if (data == NULL || model == NULL || samp == NULL){ mexPrintf("Error duplicating inputs\n"); exit(EXIT_FAILURE); } const mxLogical* params = mxGetLogicals(prhs[3]); int numExamples = 0; //then, set up the cell array pointers mxArray* exampsByUserItem = NULL; mxArray* sampkuM = NULL; mxArray* samptuM = NULL; mxArray* sampnuM = NULL; //then, the double data matrices (as vectors) double* c = NULL; double* d = NULL; double* muC = NULL; double* muD = NULL; double* mC = NULL; double* nC = NULL; double* nD = NULL; //the scalar values double c0, betaM, gammaM; c0 = betaM = gammaM = 0; int length_mC, length_nC, length_kM, length_muC; length_mC = length_nC = length_kM = length_muC = 0; //the uint32_t numerical matrices uint32_t* kM = NULL; uint32_t* kU = NULL; const double* resids = mxGetPr(mxGetField(samp, 0, "resids")); const double d0 = (*mxGetPr(mxGetField(model, 0, "d0"))); const double sigmaSqd = (*mxGetPr(mxGetField(model, 0, "sigmaSqd"))); const double sigmaSqd0 = (*mxGetPr(mxGetField(model, 0, "sigmaSqd0"))); const double invsigmaSqd = (*mxGetPr(mxGetField(model, 0, "invsigmaSqd"))); const double invsigmaSqd0 = (*mxGetPr(mxGetField(model, 0, "invsigmaSqd0"))); if (params[0]){ //isItemTopic == true mexPrintf("Sampling dishes for users\n"); numExamples = (*mxGetPr(mxGetField(data, 0, "numUsers"))); //dereference to get value of numUsers exampsByUserItem = mxGetField(data, 0, "exampsByUser"); c = mxGetPr(mxGetField(samp, 0, "c")); d = mxGetPr(mxGetField(samp, 0, "d")); sampkuM = mxGetField(samp, 0, "kuM"); samptuM = mxGetField(samp, 0, "tuM"); sampnuM = mxGetField(samp, 0, "nuM"); length_mC = mxGetN(mxGetField(samp, 0, "mC")); mC = (double*)mxMalloc((length_mC)*sizeof(double)); memcpy(mC, mxGetPr(mxGetField(samp, 0, "mC")), length_mC*sizeof(double)); length_nC = mxGetN(mxGetField(samp, 0, "nC")); nC = (double*)mxMalloc((length_nC)*sizeof(double)); memcpy(nC, mxGetPr(mxGetField(samp, 0, "nC")), length_nC*sizeof(double)); nD = mxGetPr(mxGetField(samp, 0, "nD")); //we don't modify nD, so it's OK to just have it be a pointer length_kM = mxGetN(mxGetField(samp, 0, "kM")); kM = (uint32_t*)mxMalloc((length_kM)*sizeof(uint32_t)); memcpy(kM, (uint32_t*)mxGetData(mxGetField(samp, 0, "kM")), length_kM*sizeof(uint32_t)); kU = (uint32_t*)mxGetData(mxGetField(samp, 0, "kU")); //not being modified length_muC = mxGetN(mxGetField(samp, 0, "muC")); muC = (double*)mxMalloc((length_muC)*sizeof(double)); memcpy(muC, mxGetPr(mxGetField(samp, 0, "muC")), length_muC*sizeof(double)); muD = mxGetPr(mxGetField(samp, 0, "muD")); c0 = (*mxGetPr(mxGetField(model, 0, "c0"))); betaM = (*mxGetPr(mxGetField(model, 0, "betaM"))); gammaM = (*mxGetPr(mxGetField(model, 0, "gammaM"))); } else{ //isItemTopic == false mexPrintf("Sampling dishes for items\n"); numExamples = (*mxGetPr(mxGetField(data, 0, "numItems"))); exampsByUserItem = mxGetField(data, 0, "exampsByItem"); c = mxGetPr(mxGetField(samp, 0, "d")); d = mxGetPr(mxGetField(samp, 0, "c")); sampkuM = mxGetField(samp, 0, "kjU"); samptuM = mxGetField(samp, 0, "tjU"); sampnuM = mxGetField(samp, 0, "njU"); length_mC = mxGetN(mxGetField(samp, 0, "mD")); mC = (double*)mxMalloc((length_mC)*sizeof(double)); memcpy(mC, mxGetPr(mxGetField(samp, 0, "mD")), length_mC*sizeof(double)); length_nC = mxGetN(mxGetField(samp, 0, "nD")); nC = (double*)mxMalloc((length_nC)*sizeof(double)); memcpy(nC, mxGetPr(mxGetField(samp, 0, "nD")), length_nC*sizeof(double)); nD = mxGetPr(mxGetField(samp, 0, "nC")); length_kM = mxGetN(mxGetField(samp, 0, "kU")); kM = (uint32_t*)mxMalloc((length_kM)*sizeof(uint32_t)); memcpy(kM, (uint32_t*)mxGetData(mxGetField(samp, 0, "kU")), length_kM*sizeof(uint32_t)); kU = (uint32_t*)mxGetData(mxGetField(samp, 0, "kM")); length_muC = mxGetN(mxGetField(samp, 0, "muD")); muC = (double*)mxMalloc((length_muC)*sizeof(double)); memcpy(muC, mxGetPr(mxGetField(samp, 0, "muD")), length_muC*sizeof(double)); muD = mxGetPr(mxGetField(samp, 0, "muC")); c0 = (*mxGetPr(mxGetField(model, 0, "d0"))); betaM = (*mxGetPr(mxGetField(model, 0, "betaU"))); gammaM = (*mxGetPr(mxGetField(model, 0, "gammaU"))); } mexPrintf("Initialized values successfully\n"); //outputs mxArray* sampkuM_out = mxCreateCellMatrix(numExamples, 1); omp_set_num_threads(MAX_NUM_THREADS); gsl_rng** rngs = getRngArray(); //RNG part int thread = omp_get_thread_num(); const gsl_rng* rng = rngs[thread]; //#pragma omp parallel for for (int uu = 0; uu < numExamples; uu++){ mwSize kuM_size = mxGetN(mxGetCell(sampkuM, uu)); mwSize tuM_size = mxGetN(mxGetCell(samptuM, uu)); mwSize TuM = mxGetN(mxGetCell(sampnuM, uu)); //initialize TuM when going to new user; TuM = nuM_size uint32_t* kuM = (uint32_t*)mxMalloc((kuM_size)*sizeof(uint32_t)); //needs to be modified, so allocating on heap memcpy(kuM, (uint32_t*)mxGetData(mxGetCell(sampkuM, uu)), kuM_size*sizeof(uint32_t)); //copying onto heap uint32_t* tuM = (uint32_t*)mxMalloc(tuM_size*sizeof(uint32_t)); memcpy(tuM, (uint32_t*)mxGetData(mxGetCell(samptuM, uu)), tuM_size*sizeof(uint32_t)); uint32_t* examps = (uint32_t*)mxGetData(mxGetCell(exampsByUserItem, uu)); int numExamples_uu = mxGetN(mxGetCell(exampsByUserItem, uu)); //size of examps uint32_t** tuM_cell = (uint32_t**)mxMalloc(TuM*sizeof(uint32_t*)); uint32_t tuM_cell_size[TuM]; for (int i = 0; i < TuM; i++ ){ tuM_cell[i] = NULL; tuM_cell_size[i] = 0; } if (tuM_size != numExamples_uu){ mexPrintf("Error: size of tuM matrix for user %d is %d; it should equal numExamples, which is %d\n", uu, tuM_size, numExamples_uu); exit(EXIT_FAILURE); } for (mwSize ee_i = 0; ee_i < numExamples_uu; ee_i++){ //numExamples_uu == tuM_size; assembling all the examples for this user sorted by table in a cell array if (tuM[ee_i] > TuM){ mexPrintf("Error: table number for user %d, example %d, exceeds number of tables!\n", uu, ee_i); } uint32_t* tuM_cell_table = tuM_cell[tuM[ee_i]-1]; if (tuM_cell_table == NULL){ //i.e., the entry is empty thus far tuM_cell_table = (uint32_t*)mxMalloc(sizeof(uint32_t)); tuM_cell_table[0] = examps[ee_i]; tuM_cell[tuM[ee_i]-1] = tuM_cell_table; tuM_cell_size[tuM[ee_i]-1] = 1; } else { int orig_size = tuM_cell_size[tuM[ee_i]-1]; uint32_t* tuM_cell_expanded = (uint32_t*)mxRealloc(tuM_cell_table, (orig_size+1)*sizeof(uint32_t)); if (tuM_cell_expanded){ tuM_cell_expanded[orig_size] = examps[ee_i]; tuM_cell[tuM[ee_i]-1] = tuM_cell_expanded; tuM_cell_size[tuM[ee_i]-1] += 1; } else { mexPrintf("Could not enlarge tuM cell array for user %d, example %d\n", uu, ee_i); } } } //sample a new dish for each table for (mwSize tt = 0; tt < TuM; tt++ ){ uint32_t* examp_tuM = tuM_cell[tt]; int table_size = tuM_cell_size[tt]; if (table_size > 0){ int old_k = kuM[tt] - 1; //update global dish sufficient stats immediately mC[old_k] -= 1; if (mC[old_k] < 0){ mC[old_k] = 0; } for (mwSize ee_i = 0; ee_i < table_size; ee_i++){ //loop through all examples assigned to table uint32_t ee = examp_tuM[ee_i] - 1; double residC = (params[1]) ? resids[ee] - muD[kU[ee]-1] : resids[ee] - d[kU[ee]-1]; muC[old_k] = updateCRFMu(muC, nC, residC, old_k, false, model); //remove current rating from global sufficient stats //NOTE! this is a hack if (fabs(muC[old_k]) > 30){ int sign = (muC[old_k] > 0) - (muC[old_k] < 0); muC[old_k] = sign*30; } nC[old_k] -= 1; } int new_k = sampleDishFull(examp_tuM, resids, mC, muC, muD, kU, nC, nD, betaM, c0, sigmaSqd, invsigmaSqd, invsigmaSqd0, length_mC, table_size, rng); //skipping if condition that checks if length(new_k) > 1 int empty_dish = linearSearchDouble(nC, 0, length_nC); //see what table we selected if (empty_dish > -1){ new_k = empty_dish; } //if empty_dish is found, then set new_k to it kuM[tt] = new_k + 1; //+1 to be consistent with matlab notations if (new_k + 1 > length_mC){ //length_mC tells us number of active dishes right now double* mC_expanded = (double*)mxRealloc(mC, (length_mC+1)*sizeof(double)); if (mC_expanded) { mC = mC_expanded; } length_mC++; mC[new_k] = 0; //new dish } mC[new_k] += 1; if (new_k + 1 > length_nC){ double* muC_expanded = (double*)mxRealloc(muC, (length_muC+1)*sizeof(double)); if (muC_expanded) { muC = muC_expanded; } double* nC_expanded = (double*)mxRealloc(nC, (length_nC+1)*sizeof(double)); if (nC_expanded) { nC = nC_expanded; } length_nC++; length_muC++; muC[new_k] = d0 * sigmaSqd / sigmaSqd0; nC[new_k] = 0; } for (mwSize ee_i = 0; ee_i < table_size; ee_i++){ uint32_t ee = examp_tuM[ee_i] - 1; kM[ee] = new_k+1; double residC = (params[1]) ? resids[ee] - muD[kU[ee]-1] : resids[ee] - d[kU[ee]-1]; muC[new_k] = updateCRFMu(muC, nC, residC, new_k, true, model); //NOTE: this is a hack! if (fabs(muC[new_k]) > 30){ int sign = (muC[new_k] > 0) - (muC[new_k] < 0); muC[new_k] = sign*30; } nC[new_k] += 1; } } } //close loop that goes through the tables for a given user mxArray* kuM_out; kuM_out = mxCreateNumericMatrix(1, TuM, mxUINT32_CLASS, mxREAL); if (kuM_out){ mxSetPr(kuM_out, kuM); mxSetCell(sampkuM_out, uu, kuM_out); } } //close loop over all users //set up outputs for remaining variables mxArray* mC_out = mxCreateDoubleMatrix(1, length_mC, mxREAL); mxArray* nC_out = mxCreateDoubleMatrix(1, length_nC, mxREAL); mxArray* muC_out = mxCreateDoubleMatrix(1, length_muC, mxREAL); mxArray* kM_out = mxCreateNumericMatrix(1, length_kM, mxUINT32_CLASS, mxREAL); mxSetPr(mC_out, mC); mxSetPr(nC_out, nC); mxSetPr(muC_out, muC); mxSetPr(kM_out, kM); plhs[0] = sampkuM_out; plhs[1] = mC_out; plhs[2] = nC_out; plhs[3] = muC_out; plhs[4] = kM_out; mexPrintf("Finished sampling dishes\n"); }