'Global' Variables in a guide GUI

9 visualizzazioni (ultimi 30 giorni)
Marcus Blackburn
Marcus Blackburn il 28 Mar 2017
Commentato: Rik il 30 Ott 2020
I have a GUI guide function, with multiple buttons. I want each button to change a 'global' variable to a different value. How do I go about declaring the variable correctly, and assigning the values correctly?

Risposta accettata

Jan
Jan il 28 Mar 2017
Modificato: Jan il 28 Mar 2017
Using global variables is a bad idea in general. They impede the debugging and the increase the level of complexity. You find many corresponding discussions here in the forum, but this problem concens other programming languages also. Ask an internet search engine for details.
But of course it is possible:
  • Define the global variables in each function, which needs to access them:
function y = myComputations(x)
global gParameter
y = gParameter * x;
end
  • This is done inside the callbacks also:
function Button1_Callback(hObject, EventData, handles)
global gParameter
gParameter = 1;
end
function Button2_Callback(hObject, EventData, handles)
global gParameter
gParameter = 2;
end
  • If you need the variable in so base workspace, define them as global here also.
If you need the variable in the base workspace only, e.g. as input for a Simulink method, do not define it as global but using:
function Button1_Callback(hObject, EventData, handles)
assignin('base', 'gParameter' 1);
end
This is not as evil as global variables, but you cannot trace the source of the current value of these variables reliably also.
If 'global' means, that the variable needs to be shared between callbacks of a figure only, use either set/getappdata, guidata or the 'UserData' of the corrsponding GUI element. This allows e.g. to run two instances of the same GUI without conflicts. Please ask, if you need further explanations for this.
  6 Commenti
Gopinath Karuppannan
Gopinath Karuppannan il 30 Ott 2020
How can we alter the color of each string of gparameter? especially it should be different colors
Rik
Rik il 30 Ott 2020
Do you mean in the editor? Or do you mean the values of that variable?
It also sounds like you missed the advice to avoid global variables.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Interactive Control and Callbacks in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by