Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab variables show 'reference-like' behavior when copied and passed to a mex file

I have a mex file (compiled in VS2010, Matlab 2010b) which accepts a variable, and change it. For example, in the mex file it looks like:

double *fp = (double *)mxGetPr (prhs[0]);
*fp = someDoubleValue;

In order to compare the Matlab implementation and the mex implementation, I make a copy of the variable before calling the mex file:

var_mex = var;
mymex (var_mex);

To my surprise, both var_mex and var change (to the same value of course), as if I created a reference to var and not a copy of it.

Is this a known issue? How can I convince Matlab to copy the variable?

EDIT

Since I suspected that this issue is a result of Matlab optimizing its memory management, I did some "do nothing" calculation on var before calling the mex file, i.e

var=var+1;
var=var-1;

and indeed it solves the problem. I would still be glad to get some information (or other suggestions) on this, if someone encountered it as well.

like image 999
Itamar Katz Avatar asked Jan 24 '12 10:01

Itamar Katz


1 Answers

In MATLAB, most variables are passed around as if they are being passed by value. The notable exception to this is that instances of classes that inherit from handle are explicitly passed by reference.

There's a blog entry here which goes into some detail about this.

So, when you execute

var_mex = var;

You end up with var_mex referring to the same data as var.

When you're writing to an mxArray inside a mex function, you have great power to break things because you're given the underlying address of the data. If you modify an element of the prhs array, you might inadvertently end up modifying other variables sharing the same data. So, don't do that. In fact, the mex doc explicitly tells you not to do that.

The reason that the var + 1 trick works is that by modifying the data, you're forcing MATLAB to make a copy of the data.

like image 195
Edric Avatar answered Nov 05 '22 03:11

Edric