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?
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 properties data end methods function h = myClass(data) h.data = data ; end end end
Then defining a function (which could be a method) like
function myFunction(h) h.data = h.data+2; end
lets you do something like
h = myClass(0); myFunction(h); h.data ans = 2
of course things like h+2 will not work unless you implement a plus method.
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.
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.
No, there is no way to pass a variable by reference. See Memory Management for Functions and Variables.
Handle objects, http://www.mathworks.se/help/matlab/matlab_oop/user-defined-classes.html, are passed by "reference".
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; end
function SET(datain) data =datain; end end
I saw something like this for making linked lists in matlab on stack overflow.