Can MATLAB pass by reference?

How does MATLAB deal with this?

1 comentario

E65EnyOwC
E65EnyOwC el 14 de Sept. de 2018
Check out: "How MATLAB Allocates Memory" in the Matlab help files

Iniciar sesión para comentar.

 Respuesta aceptada

Doug Hull
Doug Hull el 18 de En. de 2011

22 votos

If you are attempting to use pass-by-reference to modify the input argument passed into a function, the answer to the question depends on whether the input is a handle object or a value object. The two types of objects are described in the Object-Oriented Programming
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/brfylq3.html and Programming Fundamentals http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brtm8si.html sections of the documentation. By default, objects (including matrices, arrays, etc. of the built-in data types) are value objects.
Handle objects do exhibit reference behavior when passed as function arguments; value objects do not. When you pass a handle object to a function, MATLAB still copies the value of the argument to the parameter variable in the function (with one bit of subtlety; see below.) However, all copies of a handle object refer to the same underlying object.
If a function modifies a handle object passed as an input argument, the modification affects the object referenced by both the original and copied handles. In this case, the function does not need to return the result to be reassigned.
If instead you are attempting to use pass-by-reference to avoid unnecessary copying of data into the workspace of the function you're calling, you should be aware that MATLAB uses a system commonly called "copy-on-write" to avoid making a copy of the input argument inside the function workspace until or unless you modify the input argument. If you do not modify the input argument, MATLAB will avoid making a copy. For instance, in this code:
function y = functionOfLargeMatrix(x)
y = x(1);
MATLAB will not make a copy of the input in the workspace of functionOfLargeMatrix, as x is not being changed in that function. If on the other hand, you called this function:
function y = functionOfLargeMatrix2(x)
x(2) = 2;
y = x(1);
then x is being modified inside the workspace of functionOfLargeMatrix2, and so a copy must be made.
For more information on this behavior, read this posting http://blogs.mathworks.com/loren/2006/05/10/memory-management-for-functions-and-variables/ on Loren Shure's blog.
[From the MATLAB FAQ of Ancient Times]

7 comentarios

Richard Crozier
Richard Crozier el 13 de Dic. de 2017
What about:
var = myfunc (var)
var(1) = 1;
end
x = zeros (10000, 10000);
x = myfunc (x);
Is Matlab's copy-on-write smart enough to recognize this kind of thing and avoid copying the array?
Philip Borghesani
Philip Borghesani el 13 de Dic. de 2017
James Tursa
James Tursa el 13 de Dic. de 2017
You need to pay special attention to where you are making the call from. If you make this call not from within a function (e.g. the command line), then a temporary deep data copy WILL be created. If you make this call from within a function, then the deep data copy WILL NOT be created. E.g., from the command line (prpi is a simple mex function that displays the variable and data addresses):
Using this file:
% File myfunc.m
function var = myfunc (var)
var(1) = 1;
prpi(var);
end
From the command line:
>> x = zeros (10000, 10000);
>> prpi(x)
mxArray address = 07C85DB0
pr = 26EF0030
>> x = myfunc(x);
mxArray address = 07C87438
pr = 7FFF0030
>> prpi(x)
mxArray address = 07C85DB0
pr = 7FFF0030
So you can see that a deep data copy was made from within myfunc.m since the pr address is different. But now do the call from within this function file:
% File myfunc_test.m
function myfunc_test
x = zeros (10000, 10000);
prpi(x);
x = myfunc(x);
prpi(x);
end
Running this function:
>> myfunc_test
mxArray address = 07C86E50
pr = 26EF0030
mxArray address = 07C87978
pr = 26EF0030
mxArray address = 07C86E50
pr = 26EF0030
The pr address is the same throughout, indicating that a deep data copy was not made from within myfunc( ).
Richard Crozier
Richard Crozier el 18 de Dic. de 2017
Thanks for the thorough answers to my comment!
Tong Zhao
Tong Zhao el 21 de Mayo de 2021
Great explanation. So basically handle objects are pass-by-reference, and all references point to the same memory location of the handle object, thus any change applied to the reference during the function call will change the original values in the handle object.
Bill Tubbs
Bill Tubbs el 22 de Oct. de 2021
Both the links in the answer seem to be broken now. Does anybody have updated URLs?
Is this one of them perhaps:

Iniciar sesión para comentar.

Más respuestas (4)

Marco
Marco el 18 de Jul. de 2012

1 voto

Is this also true for nested function calls? Cuz it seems like it only works for direct function calls. In my GUIDE gui I have a function (call it Fn_takesHandles) that takes in the figure handles and updates the axes, when called by callback functions directly works just as intended. However, I run into problems when the stack frame is not one-to-one. A callBack function calls a helper function called Auto which in turn calls Fn_takesHandles. In this case it does not work as intended. Any changes made to the figure handles by Fn_takesHandles is not persistent. How would you go about solving this problem?
Is there any way to declare pointers in matlab? Any help would be appreciated!!

1 comentario

Walter Roberson
Walter Roberson el 19 de Jul. de 2012
Editada: Walter Roberson el 14 de Sept. de 2018
There is no way to declare pointers in MATLAB (at least not for calling MATLAB functions; there are ways to copy around pointers that have been created at the C / C++ level.)

Iniciar sesión para comentar.

Jason Climer
Jason Climer el 20 de Jun. de 2017

0 votos

Is this determined during the JIT compilation or as needed, i.e., is the copy of x made upon the function call or when the program executes
x(2) = 2;
?

1 comentario

Walter Roberson
Walter Roberson el 20 de Jun. de 2017
It is generally determined when the program executes, as it is not always possible to tell ahead of time whether a value is shared or not. Especially when you consider the hidden effect of assignin() .
Also, overloading can happen at run-time: the current directory or path of an operation at the time a routine is first JIT'd is not necessarily going to be the same as during a later operation.
There are cases where MATLAB does enough analysis to establish that "update in place" can happen; I do not know enough about the mechanics of that to say how it is done taking into account overloading.

Iniciar sesión para comentar.

Mandeguz
Mandeguz el 22 de Jun. de 2017

0 votos

How about when writing MEXs? Can one pass by reference within the computational routine and pull those values back to the main MATLAB code that called the MEX?

4 comentarios

Jan
Jan el 22 de Jun. de 2017
All variables are provided by reference in a Mex function: you get only pointers to the inputs. The documented MEX functions do not allow to modify the inputs directly, but it is required to create a data copy at first. But of course in the C level there is a way to maniipulate the (potentially shared data) directly. There are several undocumented methods to handle shared data copies, see e.g. https://www.mathworks.com/matlabcentral/answers/231824-issue-with-mex-function#comment_302416 . Search for "mxCreateReference" and "mxCreateSharedDataCopy" in the net to find more details.
James Tursa
James Tursa el 22 de Jun. de 2017
Also, keep in mind that struct and cell array references are evaluated as shared data copies at the caller level before the argument is passed on to the mex routine. E.g.,
x = something;
mymex(x); <-- The address of x is passed into the mex routine
y.a = something;
mymex(y.a); <-- The address of a temporary shared data copy of y.a is passed into the mex routine
z{1} = something;
mymex(z{1}); <-- The address of a temporary shared data copy of z{1} is passed into the mex routine
If the struct or cell element hasn't been created yet (i.e., is actually NULL), then a temporary empty double variable is created on the fly and the address of that is passed in.
So, when working with struct and cell arrays, it is more efficient to pass them in as whole variables and extract the element pointers inside the mex routine to avoid those temporary shared data copies.
James Tursa
James Tursa el 14 de Sept. de 2018
Also note that as of R2015b, MATLAB passes arguments to mex routines as shared data copies (it used to pass them by reference).
James Tursa
James Tursa el 10 de En. de 2019
And as of R2018a, complex variable arguments to mex routines essentially get deep data copied in both directions if you use the -R2017a compilation model.

Iniciar sesión para comentar.

Edgar Sanchez
Edgar Sanchez el 25 de Dic. de 2018

0 votos

Maybe you can use global variables

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 18 de En. de 2011

Comentada:

el 15 de Sept. de 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by