'Global' Variables in a guide GUI

23 Ansichten (letzte 30 Tage)
Marcus Blackburn
Marcus Blackburn am 28 Mär. 2017
Kommentiert: Rik am 30 Okt. 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?

Akzeptierte Antwort

Jan
Jan am 28 Mär. 2017
Bearbeitet: Jan am 28 Mär. 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 Kommentare
Gopinath Karuppannan
Gopinath Karuppannan am 30 Okt. 2020
How can we alter the color of each string of gparameter? especially it should be different colors
Rik
Rik am 30 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by