MATLAB Answers


How to pass/share data between GUIs?

Asked by Peng Zhao on 2 Jul 2019
Latest activity Commented on by Peng Zhao on 3 Jul 2019
I am trying to make a GUI that:
1stGUI: enter the number of tasks to run, then click "next" button to open another GUI to run the task.
% --- Executes on button press in Next_Button.
function Next_Button_Callback(hObject, eventdata, handles)
% hObject handle to Next_Button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(handles.Num_Task, 'Value') ~= 0
errordlg('Input cannot be zero.','Task Num. 0')
2ndGUI: run the task for the number of times entered in the 1stGUI.
So the question is, how do I access the "number of tasks" from the 1stGUI within the 2ndGUI, and also, 2ndGUI will run "number of tasks" times, and creates a matrix as the row number is "number of tasks" to store the data.
I read about "guidata", but did not get it to work.


Sign in to comment.


1 Answer

Answer by Geoff Hayes
on 2 Jul 2019
Edited by Geoff Hayes
on 2 Jul 2019
 Accepted Answer

Peng - please see for an example of sharing data between GUIs. Your second GUI will need to be able to find the first GUI (via its tag/name) and then get the handles object for that first GUI.
In the OpenFcn of your second GUI, you could add code similar to
% get the handle of Gui1
h = findobj('Tag','Gui1');
% if exists (not empty)
if ~isempty(h)
% get handles and other user-defined data associated to Gui1
handlesGui1 = guidata(h);
% get the number of tasks
numberOfTasks = get(handlesGui1.Num_Task, 'Value')


I tried to put the following lines in my OpeningFcn of 2ndGUI:
% get the handle of GPEC_Task_Generator
h = findobj('Tag','GPEC_Task_Generator');
% if exists (not empty)
if ~isempty(h)
% get handles and other user-defined data associated to GPEC_Task_Generator
handles_GPEC_Task_Generator = guidata(h);
% get the number of tasks
NumOfTasks = get(handles_GPEC_Task_Generator.Num_Task, 'Value')
However, seems like <if ~isempty(h)> this line never met.
Am I missing anything to add in 1stGUI?
In the Property Inspector for GPEC_Task_Generator, set the HandleVisibility property to on, and confirm that the Tag property is set to GPEC_Task_Generator.
Thank you, it is now working!

Sign in to comment.