Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Pass variable by reference to function

Asked by Adam on 28 Sep 2012
Latest activity Commented on by Image Analyst on 28 May 2014

I have read that the only way to pass by reference with a function is if you pass a handle. Is there a matlab call to get the "handle" of a variable or structure?




5 Answers

Answer by Daniel on 1 Oct 2012
Accepted answer

While I think IA's answer is the better way to do it. If you really want to do what you are talking about you can create a subclass of handle.

classdef myClass < handle
		function h = myClass(data) = data	;

Then defining a function (which could be a method) like

function myFunction(h) =;

lets you do something like

h = myClass(0);
ans =

of course things like h+2 will not work unless you implement a plus method.

1 Comment

Alessandro on 27 Feb 2013

Nice post ! Matlab should have something like this as a standard object ! The problem with this class is that it still copy the value from workspace to the class but is a good workaround.

Answer by Image Analyst on 29 Sep 2012

For all practical purposes, you can get the same effect by passing the input argument back out. For example, in the function definition:

function myVariable = ChangeMyVariable(myVariable)
  myVariable = 2 * myVariable;

Then to call it, do this:

myVariable = ChangeMyVariable(myVariable);

And, obviously, myVariable could be anything, such as a structure like you mentioned. For all intents and purposes, this is the same as the code you'd use if it were pass by reference:


The net effect is you get your variable changed, it's just slightly different syntax.


Ninetrees on 27 May 2014

@Vit's reply resonated with me. I came to MATLAB with decades of software engineering experience in other languages. Passing by value or by reference was (is) an important consideration in some languages. @Vit mentioned that his program "duplicate used memory for that variable". I just did a quick test by creating a function that modified 1 element of a 1M element matrix. I toggled the assignment in the function by commenting it out. Memory decremented by ~8 MB when X(1) was changed, and not when X was not changed. /This/ is the reason that I and others have asked about passing by reference. The snippy comment by AI in 2012 didn't address this. It may have addressed the effect, but not the concern of the OP. I shouldn't have had to write a test just to fully understand what MATLAB does. This simple example should be a part of the docs, along with a clear statement that the entire passed matrix is duplicated when 1 element is changed.

M = (1.0: 1.0: 1000000);


M = Passing_by_reference_or_value_test_0100_function (M);

M (1)


function X = Passing_by_reference_or_value_test_0100_function (X)

X (1) = 2.0;
X (1)


MATLAB docs mention "smart" passing, but if passing by reference were allowed in the first place, there would be less confusion, and no need for discussions of "smart" updating of the calling variable space, nor would MATLAB need to keep track of what changed. If I passed a matrix in, say, Pascal, by reference, then modified X(1), there would be no question of how much memory was used, where the variable existed, or what was changed in the matrix. What is not clear to me is how MATLAB handles a situation where I pass in a matrix, make local changes to some elements, and /don't/ pass the matrix back to the calling frame. Does MATLAB make only local copies of the elements that changed? In that case, there is a trade-off: MATLAB bookkeeping overhead versus copying the entire matrix, which can involve putting it on a stack and popping it off a stack, both memory intensive, not to mention copying a 1 million-element matrix, and changing only a small percentage of elements. It seems from my test above that MATLAB does, indeed, make a full copy of the passed matrix. Creating a subclass of handle seems to me a wordy and inefficient alternative to simply providing pointers to variables AND|OR a "pass by reference" keyword in the function formal parm list. ~R~

James Tursa on 27 May 2014

To get the in-place memory savings to happen automatically for your example, I think the rules are you have to make the call from within another function. Otherwise, you will get the temporary double memory impact. Did you make the call from the command line?

In general, if you want in-place behavior regardless of how you call things or when/where you modify them, then you either need to derive a class from handle, or do the work in a mex routine using unofficial means.

"What is not clear to me is how MATLAB handles a situation where I pass in a matrix, make local changes to some elements, and /don't/ pass the matrix back to the calling frame. Does MATLAB make only local copies of the elements that changed?"_ _

No. if you change only 1 element of a 1GB array, MATLAB will suddenly make a 1GB deep data copy of the array first, then change the 1 element. This is the general behavior of shared data copy variables that do not derive from handle and are not part of the special in-place function syntax and calling rules noted above.

Image Analyst on 28 May 2014

I still believe the net effect, when you're not worried about running out of memory, is the same. I agree that, sure, it might do it differently, and might cause you to run out of memory for really huge arrays, and it might take longer , but for most ordinary situations your output variable will still get changed into the same value and you won't notice the difference. Again, for ordinary situations, not memory hog situations. So I don't agree that my "original reply is wrong!" I also agree that pass by reference might have some situations where it's preferable to use that method.

Image Analyst
Answer by per isakson on 28 Sep 2012
Edited by per isakson on 28 Sep 2012

No, there is no way to pass a variable by reference. See Memory Management for Functions and Variables.

Handle objects,, are passed by "reference".


Adam on 28 Sep 2012

I understand that only handles can be passed by reference. Is there a way of obtaining a handle for a variable?

per isakson on 28 Sep 2012

No, not with documented Matlab. And not with as far as I know.

Why do you want to pass by reference?

per isakson
Answer by James Tursa on 29 Sep 2012

I will ask again what others have already asked. Why do you want the "handle" to the variable? What advice we give you will depend on the answer to that question. FYI, by default MATLAB passes a shared data copy of the arguments to the function ... i.e., there is no data copy involved. So it is already efficient in that sense. But we really need to know what you are doing with the variable inside the function in order to best answer your question, and whether passing by "reference" makes sense for your application.


Adam on 1 Oct 2012

This isn't a memory question as much a code cleanliness, reuse, and good practices question as well as my own edification. I'm not looking for coding advice, but an answer to the question of if it is fundamentally possible to get the "handle" of a variable or structure?

Walter Roberson on 3 Oct 2012

If it is a question about code cleanliness, reuse, and good practices, then you are looking for coding advice, and IA's recommendation to use a return value is not "imposed" is an appropriate "good practices" response. Hidden modification of variables is not good practice; it is, for example, emphatically disallowed in Yourdon & Constantine's "Structured Design" (1979)

James Tursa
Answer by Alessandro on 16 Apr 2013

Hello I would say a possible solution is the following (without using classes):

%Reference to some matlab Data
  function reference = globaldata()
      data = [];
        reference = struct('GET',@GET,'SET',@SET);
        function dataout = GET()
            dataout = data;
        function SET(datain)
            data =datain;

I saw something like this for making linked lists in matlab on stack overflow.



Contact us