MATLAB: Problems re-transferring variables from Mex File to Matlab

mex filepisinger

I'm trying to build a mex file from a specific function in C code called quadknap.c (<http://www.diku.dk/~pisinger/quadknap.c)>. My aim is to define the variables no (= number of items), cap (=capacity), ptab (=profit matrix) and wtab (=weight matrix)in Matlab and to run the mex file with these variables as inputs.
As a result I need to get back the variables z (=value of the optimal knapsack) and xtab (=0-1 soluction vector) as outputs to work with the variables in Matlab.
The original code has no main function. Thus, I have integrated the mexFunction and included mex.h and matrix.h. The mexFunction looks like this
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
double *ptab, *wtab, *xtab;
double no, cap, z;
no = mxGetScalar(prhs[0]);
cap = mxGetScalar(prhs[1]);
ptab = mxGetPr(prhs[2]);
wtab = mxGetPr(prhs[3]);
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(1, no, mxREAL);
z = mxGetScalar(plhs[0]);
xtab = mxGetPr(plhs[1]);
quadknap(no, cap, ptab, wtab, x);
mexCallMATLAB(0, NULL, 1, &prhs[2], "disp");
return;
}
My problem is that I got back only empty arrays plhs[0] and plhs [1] in Matlab then I run the mex file. For associating pointers and arrays I followed the xtimesy.c example of the Matlab extern examples. However, it seems like there is an error in this association for the output variables I do not find.
Kind regards, Matthias

Best Answer

I doubt you are getting back "empty" arrays. I think what you meant was you are getting back arrays with only 0's in them.
The reason is that you never set the output plhs[0] or plhs[1] data areas to anything after creating them. You need to get the pointers to the data areas and then use them to put values in those areas. E.g.,
double *ptab, *wtab, *xtab, *pr;
:
pr = mxGetPr(plhs[0]);
xtab = mxGetPr(plhs[1]);
*pr = quadknap(no, cap, ptab, wtab, xtab); // Did you mean xtab as last argument?
I assumed that you meant to type xtab as the last argument, but I haven't looked over the quadknap code to see if that is an output so you will need to check this yourself. I also assumed that the return value of quadknap is the "z" you are trying to return as the 1st output.