'Global' Variables in a guide GUI

27 次查看(过去 30 天)
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?

采纳的回答

Jan
Jan 2017-3-28
编辑:Jan 2017-3-28
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 个评论
Gopinath Karuppannan
How can we alter the color of each string of gparameter? especially it should be different colors
Rik
Rik 2020-10-30
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by