MATLAB Answers


Pass variable by reference to function

Asked by Adam
on 28 Sep 2012
Latest activity Commented on by Marc Vaillant on 25 Sep 2019
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?


Sign in to comment.

6 Answers

Answer by Daniel Shub
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

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.

Sign in to comment.

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.


Hi Lucas,
the programming pattern that Image Analyst showed, namely
function Y = someFun(x, Y, z)
Y = x + Y;
involves no copying of Y at all, provided, that you
  • call it like var = someFun(x, var, y), i.e. both the function declaration and the calling function use the same variable names for input and output
  • Your MATLAB version is not too old: this optimization was introduced somewhere around 2010.
Give it a try with a large variable. You will see in the task manager no copy is done.
Hi, I tried your trick with very large matrix. By the jump in the memory consumption I can assure you it is not working by reference.
I think there is a typo in the comment by Titus Edelhofer, it should read
var = someFun(x, var, y),
rather than
var = someFun(x, Var, y),
@Royi, Which release are you running?

Sign in to comment.

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.


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?
No, not with documented Matlab. And not with as far as I know.
Why do you want to pass by reference?

Sign in to comment.

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.


Using pointers is not a hidden modification of a variable. It's a efficient practice widely used in any performing language.
Once you pass in a pointer, you lose control over whether there is a modification to the original data or not. You cannot tell from a C function declaration whether it modifies the data stored at any given pointer: at best you can hope that the person who wrote the function was diligent about putting in "const" where-ever possible.
Some languages require that every parameter to a function be marked as either input only, output only, or in/out . With such languages, there is never any surprise factor. If your goal is code cleanliness, reuse, and good practices, then you should prefer to avoid languages where the default is to permit modification of any item you have a pointer to.
I don't understand this point. If const is not used in C and C++ code for pointers passed to a function, then you should assume that the function is going to modify the data. That is what should be expected when you read such a function signature, and you can't go wrong if you make that assumption. Copy your data before passing it if you don't want your data modified and there will be no "surprises."
Also, const is more powerful that just for function signatures, it can be used to guaranty that methods of objects do not modify their member data. Code that does not obey const correctness is one of the quickest ways to determine whether or not it is code worth using.
There may be several reasons to choose other languages over C and C++, but I would argue that clarity over whether or not a function will modify datastructures passed to it is not one of them.

Sign in to comment.

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.


Sign in to comment.

Answer by Lamont Granquist on 12 Jun 2019

This isn't so much an answer but an example of why pass-by-reference would be useful. I want to pull an array of values out of an ode45 OutputFnc, the straightforward programming way to do this would be to create a closure over a local variable which was passed along with the function handle into ODE45 and have the OutputFnc update that. Since the original program is not the caller of the OutputFnc -- ode45 is -- it is not possible to use the output parameters.
T0a = [];
options = odeset('OutputFcn', @(t, y, flag) odethrust(t, y, flag, T0a, mf_bar, thrust_bar));
[t, y] = ode45(@(t, y) ode(t, y, tf0/2, thrust_bar, mf_bar, ve_bar), lgt, y0, options);
function dXdtau = ode(t, y, tau, thrust_bar, mf_bar, ve_bar)
r = y(1);
v = y(2);
m = y(3);
if m < mf_bar
T = 0;
T = thrust_bar;
drdt = v;
dvdt = - 1/r^2 + T / m;
dmdt = - T / ve_bar;
dXdtau = tau * [ drdt dvdt dmdt ]';
function status = odethrust(t,y,flag,T, mf_bar, thrust_bar)
if isempty(flag)
m = y(3);
if m < mf_bar
T = [ T 0 ];
T = [ T thrust_bar ];
status = 0;
That is a snippet out of a real program so some variables like mf_bar/ve_bar/thrust_bar/etc aren't declared. The structure of the ODE isn't terribly important other than I'm trying to access the time history of the T variable as well as the variables of integration (pretend that the simplistic way T is handled now could be arbitrarily complicated so I don't want answers that figure out the problem analytically outside of this loop -- if you can guess the problem domain, you can be sure I know that the rocket equation exists).
The important point is the way that I want to declare T0a as an empty array, and then pass that into the function handle of odethrust, which is the OutputFcn for the ode45 call.
I guarantee there's nothing wrong -- in a computer science sense -- with wanting to pass in a closure like this to accumulate state.


Sign in to comment.