#include "mex.h"
static double *t = NULL;
static int count = 0;
//we need to free the allocated memory, we do this when the mex file is
//released from memory
static void CleanUp(void)
{
mexPrintf("cleaning up\n");
//mxFree(t); this wont work
free(t);
count = 0;
}
void timestwo(double A, double *y, double *x)
{
int i,j;
//first call?
if (count == 0)
{
//if so allocate memory
//t = (double*) mxMalloc(80*sizeof(double)); wont work
t = (double*) malloc(80*sizeof(double));
for(i=0;i<80;i++)
{
//fill up t, which will never change
t[i] = (double) i;
//calculate y
y[i]=A*t[i];
}
}else
{
//timestwo was called before, so memory is allocated and t is filled,
//simple calaculte y again
for(i=0;i<80;i++)
y[i]=A*t[i];
}
count = count+1;
//copy the t vector into x
memcpy(x,t,80*sizeof(double));
mexPrintf("%i\n",count);
mexPrintf("%f\n",x[50]);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//first call?
if (t == NULL){
//if so set the cleanup routine
mexAtExit(CleanUp);
}
plhs[0] =mxCreateDoubleMatrix(80,1,mxREAL);
plhs[1] =mxCreateDoubleMatrix(80,1,mxREAL);
timestwo(mxGetScalar(prhs[0]),mxGetPr(plhs[0]),mxGetPr(plhs[1]));
}
Best Answer