MATLAB: Wait for a function to finish while the function runs GUI

functionsguipauseuiwait

Hello Everyone,
I have a function which works perfectly in itself:
function [ Main_Lang ] = Language( )
% select language page.
% runs the program in selected language.
Main_Lang = -2;
fig_1 = figure('name', 'fig_1');
% define flags for langauge selection, used for the callback function
% lang value 0 - Hebrew
% lang value 1 - English
% Hebrew button settings
lang_heb = uicontrol('style', 'pushbutton',...
'string', 'עברית',...
'fontsize', 12,...
'units','normalized',...
'position', [0.25 0.5 0.2 0.1],...
'callback', 'Main_Lang = 0; uiresume(fig_1)');
% English button settings
lang_eng = uicontrol('style', 'pushbutton',...
'fontsize', 12,...
'string', 'English',...
'units','normalized',...
'position', [0.55 0.5 0.2 0.1],...
'callback', 'Main_Lang = 1; uiresume(fig_1)');
uiwait(fig_1);
close fig_1;
end
I have two issues while running it from this Main script:
Num_Ques = 8;
[Main_Lang] = Language()
if Main_Lang == 0
Ques_arr = Choices_Heb()
end
Currently, for some reason when the function is opened by the Main, when it reached the point of the uiwait, I get this: Error using waitfor Undefined function or variable 'fig_1'.
Error using waitfor Error while evaluating UIControl Callback
While if I run the function on itself it works fine.
What I'm trying to accomplish is the the Main script will not continue until the Language function is done (since I immediately use the value I get).
Can you please advise?
Thank you!
Jasmine

Best Answer

a) This does not run if you call the function by itself. b) Your issue has to do with the callback functions of the uicontrol. Functions maintain separate workspaces and therefore fig_1 is not in the scope of the callback functions and the Main_Lang in the callback is different from the one in the Language() scope. Consider making your callbacks for the function as such:
function cBack(src,evt,mainLang,fig)
% Callbacks do not allow output variables, but you can store data in the figure itself.
set(fig,'UserData',mainLang);
% fig.UserData = mainLang; %Post 2014b syntax
uiresume(fig);
end
Now callbacks expect only the first 2 unused inputs, so make an anonymous funtion:
callBackHebrew = @(src,evt) cBack(src,evt,0,fig)
callBackEnglish = @(src,evt) cBack(src,evt,1,fig)
Now just make sure you extract the language identifier from the figure inside of the function Language()
uiwait(fig_1);
Main_Lang = get(fig_1,'UserData');
% Main_Lang = fig_1.UserData; % Post 2014b syntax
close fig_1;