MATLAB: Alter values of variables in mexFunction from within a subfunction

MATLABmex

Hello everyone,
I'm afraid this is a very basic question, but I couldn't find an answer to this, and I just don't get it working on my own:
I want to call a function minf.m via mexCallMATLAB within a subfunction minfcall, which is called from within a mexFunction. What I want to achieve is to alter the values of a and b by calling minfcall. When I run the code given below, the values of a and b displayed by mexPrintf from within minfcall are correct, but after exiting the function, the displayed values in mexFunction are the same as they were before calling minfcall.
Here's the code of the mexFunction:
#include "mex.h"
#include <string.h>
void minfcall(double *a, double *b){
mxArray *inp[1], *outp[2];
inp[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
memcpy(mxGetPr(inp[0]), a, sizeof(double));
mexPrintf("Before mexCallMATLAB:\n");
mexPrintf("a: %f\nb: %f\n", *a, *b);
mexCallMATLAB(2,outp,1,inp,"minf");
a = mxGetPr(outp[0]);
b = mxGetPr(outp[1]);
mexPrintf("After mexCallMATLAB:\n");
mexPrintf("a: %f\nb: %f\n", *a, *b);
}
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]){
double *a, *b;
a = mxGetPr(prhs[0]);
b = mxCalloc(1, sizeof(double));
minfcall(a, b);
mexPrintf("After exiting minfcall:\n");
mexPrintf("a: %f\nb: %f\n", *a, *b);
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
memcpy(mxGetPr(plhs[0]), a, sizeof(double));
plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
memcpy(mxGetPr(plhs[1]), b, sizeof(double));
}
The m-File does the following:
function [a, b] = minf(a)
a = 2 * a;
b = 2 * a;
end
Can you tell me what I am doing wrong here?
Thank you very much for your support!

Best Answer

You probably need to do this:
/* Copy the outputs of minf into a and b */
*a = *(mxGetPr(outp[0]));
*b = *(mxGetPr(outp[1]));
Instead of this:
/* Replace the pointer addresses of a and b with those of the output mxArrays */
a = mxGetPr(outp[0]);
b = mxGetPr(outp[1]);
Also, remember to destroy the output mxArrays at the end of minfcall so you're not leaking memory:
mxDestroyArray(outp[0]);
mxDestroyArray(outp[1]);