MATLAB: Trouble saving a variable to a base GUI and accessing it in another.

guimultiple windowspassing variables

I have 3 GUIs:
  1. Gui1 is the base window.
  2. Gui2 is a callback from a button in Gui1, gets user input, then attempts to save the input as a variable in Gui1.
  3. Gui3 is a callback from a button in Gui1 and uses the data saved from Gui2.
Below are outlines of the code I have.
:
function GUI1
% create figure
fig = figure(<figure settings>,'tag','Main Window');
% figure handles
mainWindow = guihandles(fig);
% create an empty variable
mainWindow.data = [];
% create two buttons, button2 and button3 to call Gui2 and Gui3, respectively\
% set their callbacks accordingly
set(mainWindow.button2,'callback',{@Gui2,mainWindow});
set(mainWindow.button3,'callback',{@Gui3,mainWindow});
% save the handle
guidata(fig,mainWindow);
end
Gui2:
function Gui2
% code gets user input in a variable userInput
% find object from tag
saveFig = findobj('tag','Main Window');
% get the handles of Gui1's figure
target = guidata(saveFig);
% set the data
target.data = userInput;
% save handle
guidata(saveFig,target);
end
I'm running Gui1 first, then Gui2 to get the data and save it into Gui1. After that, I'm trying to pass the saved variable from Gui1 into Gui3, but somewhere along the way it appears Gui2 failed to pass the variable into Gui1, so the "data" field is still showing as [].
Any tips? I'm really not sure where I'm going wrong here.
EDIT: I just figured it out, the issue was that I was trying to recall data in Gui3 by directly accessing the handles from the callback setting in the main window, which meant that the updated mainWindow handles weren't being accessed. I changed it so whenever I need the stored variables I would use findobj and guidata to obtain the updated mainWindow handles.

Best Answer

Pass data back to the main routine
function data = Gui2
% Code.
% Now, call gui2 in main program:
data = Gui2() % Get data back out
mainWindow.data = data; % Assign data to handles structure in main program.