Create a global variable in a GUI

70 vues (au cours des 30 derniers jours)
Edward
Edward le 28 Sep 2013
Commenté : Miguel Reyes le 24 Août 2018
Im making a gui which has a two buttons:
function button_browse_Callback(hObject, eventdata, handles)
filename = uigetfile
function button_load_Callback(hObject, eventdata, handles)
fid=fopen(filename,'rt');
....etc
but I cant do the above because button_load_Callback does not have access to filename.
how can I pass the filename from button_browse_callback to button_load_callback?

Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 28 Sep 2013
Modifié(e) : Azzi Abdelmalek le 28 Sep 2013
You don't need global variables, use guidata
function button_browse_Callback(hObject, eventdata, handles)
filename = uigetfile
...
handles.filename=filename
guidata(hObject,handles)
%-------------------------------------------------------------------------------------------------------
function button_load_Callback(hObject, eventdata, handles)
filename=handles.filename
fid=fopen(filename,'rt');
...
  4 commentaires
Khine zar
Khine zar le 17 Mar 2018
thank you !.... Your answer is helpful for me !
Miguel Reyes
Miguel Reyes le 24 Août 2018
Thanks! for your practical idea

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 28 Sep 2013
Modifié(e) : Image Analyst le 26 Juin 2015
Another way is to declare the variables global in every function that needs to access them.
function button_browse_Callback(hObject, eventdata, handles)
global baseFileName folder;
[baseFileName, folder] = uigetfile();
function button_load_Callback(hObject, eventdata, handles)
global baseFileName folder;
fullFileName = fullfile(folder, baseFileName);
fid=fopen(fullFileName ,'rt');
Any function that declares the variables baseFileName and folder as global will be able to see the variables. They can be created and changed in any function that has that global declaration line. Functions that do not have the global declaration line will not be able to see those variables.
  6 commentaires
Stephen23
Stephen23 le 21 Sep 2015
Modifié(e) : Stephen23 le 21 Sep 2015
John
John le 21 Sep 2015
Hi Stephen, i know used guidata for passing values between several GUIs but now i want to execute a complex function wihtin a GUI and this function doesnt have input parameters but works with globally defined variables. Thats why i would like to do it this easy way...i thought declaring variables as global in the opening function of the mainGUI would make them visible all over the main GUIs callbacks and also for the children of the parent mainGUI... I am wrong with that right? so i always have to declare them again vefore i have access....

Connectez-vous pour commenter.

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by