MATLAB: How to use Matlab “data=load(filename)” in a Mex file

mex load

I have been given a C code mex file that works fine. While processing is going on in the mex file, I want to load in more mat-file data. In matlab this would be "data = load(filename)". How can I do this?

Best Answer

Basically, set up the appropriate mxArray variables then use mexCallMATLAB. E.g.,
mxArray *filename, *data;
char cfilename[] = "insert_mat_filename_here";
filename = mxCreateString(cfilename);
mexCallMATLAB(1,&data,1,&filename,"load");
mxDestroyArray(filename);
// use data
mxDestroyArray(data);
The above code snippet loads the mat stuff inside the mex routine, not back to the calling workspace. If you want to get it back to the calling workspace you will need to return data as one of the plhs variables (and not destroy it).