How to change original variable inside function?

208 views (last 30 days)
I want to change variable inside function, something simular to this c++ function:
void f(int &a){a+=2;}
I've heard handles can be useful here, but anything I tried only generated copy of variable, and was unable to change original. I'd use simple return values, but it's callback function and I can't return anything, at least as far as I know. Please help.

Accepted Answer

Stephen23
Stephen23 on 9 May 2015
Edited: Stephen23 on 11 May 2015
MATLAB is pass-by-value, with some fancy inbuilt stuff to intelligently minimize memory usage. Variables are copied when they are changed, so when you make a change to that variable it will create a new copy.
If you need this variable outside of the callback, then you need to pass it somehow. There are several helper functions and ways of doing this:
And if those do not help you then you should do a search of this forum, as this topic has been dealt with a thousand times before.

More Answers (1)

Image Analyst
Image Analyst on 9 May 2015
Simply pass back the variable in the output list
function a = doubleit(a)
a = 2 * a; % Change a.
Now, in the calling routine
a = 5
a = doubleit(a);
Now a will have the new value you set it to inside the function, 10 in this case);
  6 Comments
Lunky Sucipto
Lunky Sucipto on 11 May 2022
@Image Analyst In your doubleit example, you use 'a' as both input and output. However my case is different:
function object = find(k)
% find the object from my data structure that has property k
object = item_with_property_k
end
After finding the object, I now need to modify the object. How can I do this? I'm going to read libpointer now, but I'm not sure about anything right now.
Image Analyst
Image Analyst on 11 May 2022
@Lunky Sucipto just modify it. For example if it's a structure and you want to add a field "foundIt", just do
object.foundIt = true;

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!