Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined variable out of nowhere

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?

like image 384
ignorant Avatar asked Nov 18 '25 08:11

ignorant


1 Answers

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.

like image 166
Dang Khoa Avatar answered Nov 20 '25 21:11

Dang Khoa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!