MATLAB: Passing by reference an object in a function

passing by reference

I have a simple question about passing a variable by reference in Matlab. from the forums I have seen, there is no clear answer about that. From what I have understood( but may be I am wrong), let say that you have a function that take a table A and want to change in this table only the h line. if I do
function arg=myFunction(A,h)
A(h,:) = A(h,:)+2;
end
and call myFunction(A,3), A will not be changed. When specifying myFunction like this
function A=myFunction(A,h)
A(h,:) = A(h,:)+2;
end
and calling myFunction(A,3), A is changed. But from what I understood of what matlab does, matlab is copying A, then change in the copy the h lines of A, then provide output the copy. First question: Is this true or not? and if yes, is there a way to pass it by reference, which means directly modifying A. I know that by doing directly A(h,:) = A(h,:)+2; in the command line, I can obtain the same result. but on some applications, when A is very large, like Gibbs sampler, where i want to sample sequentially each line of A conditionnally to the other ones, it looks to me that copying for every call the large dataset A is inefficient. I am not an expert of matlab, please excuse if the question is stupid.

Best Answer

For inplace operations on data using functions, see this Blog by Loren:
Basically, there are rules you must follow for the function signature, and you must call the function from within another function.
Regarding your question about what MATLAB normally does for an arbitrary function argument, the basic answer is this:
If the function is a mex routine, MATLAB passes the address of the original variable (i.e., not a shared data copy). The mex routine is expected to treat all input arguments as read-only.
If the function is a m-file and the variable is not an OOP object derived from handle, MATLAB passes a shared data copy of the variable (i.e., a new variable but no data copy yet). If the function subsequently changes the passed variable, the variable is first unshared (i.e., a data copy takes place) and then the changes are made to this newly unshared variable.
If the function is a m-file and the variable is an OOP object derived from handle, MATLAB basically allows the function to make changes to the variable inplace (i.e., data is allowed to be altered inplace with no data copy).
Note that struct and cell array references (e.g., mystruct.field1 or mycell{3}) always create a temporary shared data copy of the field or cell element. So if you have this expression as an agrument a temporary shared data copy will always be passed, even to a mex routine.;
Loren's Blog talks about how to alter some of this behavior to get MATLAB to operate inplace in some circumstances.