Question

I have MALTAB application with GUIDE interface, in OpeningFcn function which is executed before GUI is made visible i have defined such global variable:

global P1;
P1 = [];

Then I have timer function executing every 2 sec, at the very beginning of this function is:

handles=guidata(hObj);
global P1;

After that two lines function makes some calculations using P1 variable. everything was working fine for couple of hours and then suddenly I occurred this message:

??? Error while evaluating TimerFcn for timer 'timer-1'

Undefined function or variable "P1".

and application stopped. I'd understand index out of range error or something similar but undefined variable? How is that even possible?

Was it helpful?

Solution

Per the documentation for global:

To use a global within a callback, declare the global, use it, then clear the global link from the workspace. This avoids declaring the global after it has been referenced. For example,

cbstr = sprintf('%s, %s, %s, %s, %s', ...
   'global MY_GLOBAL',                ...
   'MY_GLOBAL = 100',                 ...
   'disp(MY_GLOBAL)',                 ...
   'MY_GLOBAL = MY_GLOBAL+1',         ...
   'clear MY_GLOBAL');

uicontrol('style', 'pushbutton', 'CallBack', cbstr, ...
   'string', 'count')

That being said, there typically is never a need to use a global variable. For GUIs built with GUIDE, consider using setappdata to access your variables across functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top