'Global' Variables in a guide GUI

27 ビュー (過去 30 日間)
Marcus Blackburn
Marcus Blackburn 2017 年 3 月 28 日
コメント済み: Rik 2020 年 10 月 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
Gopinath Karuppannan 2020 年 10 月 30 日
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 Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by