How to change original variable inside function?

20 vues (au cours des 30 derniers jours)
John Smith
John Smith le 9 Mai 2015
Commenté : Image Analyst le 11 Mai 2022
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.

Réponse acceptée

Stephen23
Stephen23 le 9 Mai 2015
Modifié(e) : Stephen23 le 11 Mai 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.

Plus de réponses (1)

Image Analyst
Image Analyst le 9 Mai 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 commentaires
Lunky Sucipto
Lunky Sucipto le 11 Mai 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 le 11 Mai 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;

Connectez-vous pour commenter.

Catégories

En savoir plus sur Use Prebuilt MATLAB Interface to C++ Library dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by