Global variable keeps initialising again and again when I want it to only initialise once.

5 views (last 30 days)
I have a GUI in MATLAB with a pushbutton called plot. When I click on plot as expected a figure appears. But my doubt is this. I want a global variable which is initialized to 1, the first time I run the GUI and then increment by 1 every time I press plot. I tried to do this but my global variables keeps initializing back to 1 every time when I press plot. I dont want that. I want that global variable to be initialized only one when I run the GUI and must increment every time I press plot. How can I do this. Kindly help me. Thanking You.

Accepted Answer

Jan
Jan on 17 Jan 2019
Avoid globals. As you can see already, they confuse programmers and impede the debugging. Do not use globals. For tiny codes globals can look like they solve a problem efficiently, but as soon as the codes grow or as you use different tools (maybe written by different programmers), the confusion is perfect. So implement your solution without globals in general. Globals are evil.
Do you press the same button to create the new figures? Then use e.g. the UserData of this button:
function ButtonCallback(objectH, EventData, handles)
UD = get(objectH, 'UserData');
if isempty(UD)
UD = 0;
end
UD = UD + 1;
set(objectH, 'UserData', UD);
disp(UD)
end
Now UD is increased by one each time the button is pressed.
You can store the number in the UserData of the figure also, or inside the handles struct - then update this struct by guidata, such that the update is stored in the ApplicationData of the figure.
If you really do not see a way to avoid globals or love them for unknown reasons, use them correctly:
  • Create a unique name, not a single character
  • Add the global statement in all functions, which use this variable
  • Care for a well defined location, where this global variable is initialized
Your description sounds, like you call something like this repeatedly by accident:
global X
X = 0
To help you to find the problem, we need to see the code.
  3 Comments
Rik
Rik on 17 Jan 2019
Read the documentation if you want to learn about this function. The Matlab doc is actually one of the better ones for programming languages.

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Products


Release

R2014a

Community Treasure Hunt

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

Start Hunting!