How to change original variable inside function?
20 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
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:
http://matlab.wikia.com/wiki/FAQ#How_can_I_share_data_between_callback_functions_in_my_GUI.28s.29.3F
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.
0 commentaires
Plus de réponses (1)
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
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
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;
Voir également
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!