pass value between two callback function in matlab GUI - matlab

I have 2 pushbutton. If i press one infinte loop will be running and if i press other loop must break. please some help in code.
Thanks in advance

Are you using GUIDE or a "programmatic" gui? The following is a little example for a programmatic gui; similar concepts may apply for GUIDE. (I personally like the added flexibility of the programmatic gui route, plus I always end up irrevocably breaking any GUIDE gui's I create...)
Anyway, a few things to note in this example:
use of the gui's figure handle UserData field to store "global" information. This is a way to pass data between callbacks.
the pause statement within the "infinite" loop is needed so that the interrupt from cb_button2 is processed. From Matlab help: "If the Interruptible property of the object whose callback is executing is on , the callback can be interrupted. However, it is interrupted only when it, or a function it triggers, calls drawnow, figure, getframe, pause, or waitfor."
function my_gui(varargin)
mainfig = figure;
out.h_button1 = uicontrol(mainfig,...
'Style','pushbutton',...
'Units','Normalized',...
'Position',[0,0.5,1,0.5],...
'String','Button 1',...
'Callback',#cb_button1);
out.h_button2 = uicontrol(mainfig,...
'Style','pushbutton',...
'Units','Normalized',...
'Position',[0,0,1,0.5],...
'String','Button 2',...
'Callback',#cb_button2);
out.button2_flag = 0; %flag indicating whether button 2 has been pressed yet
set(mainfig,'UserData',out);%store "global" data in mainfig's UserData (for use by callbacks)
function cb_button1(varargin)
out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
while ~out.button2_flag
disp('Aaaahhh, infinite loop! Quick press Button 2!');
out = get(gcbf,'UserData'); %reload "global" data
pause(0.1); %need this so this callback may be interrupted by cb_button2
end
disp('Thanks! I thought that would never end!');
function cb_button2(varargin)
out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
out.button2_flag = 1;
set(gcbf,'UserData',out); %save changes to "global" data

Related

Moving control out of a loop when user presses a specific key? [duplicate]

This question already has answers here:
Detect Keyboard Input Matlab
(4 answers)
Closed 6 years ago.
I am using an infinite loop in my code.
while 1
% many statements/computation...
...
...
end
I want my control to come out of the loop when a user presses a specific key, say Spacebar.
I've tried the solution given here but no luck. Figure window does not open.
You have two routes you can take.
1) You can take even-driven approach and register KeyPressFcn callback for the current figure. The catch is that Matlab is single threaded*, so as long as your loop continuously executes some code, event will not be handled. A workaround would be to insert either drawnow or pause statements within your loop. That will halt the main thread execution and would process outside events, such as our key press. In the callback you would need to change the state of some flag, e.g. an object property / appdata of some graphics handle, or even a global variable (which I would advise against). You would then be able to query from within the loop and break if you see the flag changing.
function test()
hFig = figure();
setappdata(hFig, 'space_pressed', false);
set(hFig, 'KeyPressFcn', #keyPressedFcn);
while true
A = randn(10000); % doing some stuff
pause(0.01);
flag = getappdata(hFig, 'space_pressed');
if flag
break;
end
fprintf('Still running...\n');
end
fprintf('Finished!\n');
end
function keyPressedFcn(hFig, event)
fprintf('Pressed character: "%s"...\n', event.Character);
if strcmp(event.Character, ' ')
setappdata(hFig, 'space_pressed', true);
end
end
Sample output:
>> test
Still running...
Still running...
Pressed character: "h"...
Still running...
Still running...
Pressed character: " "...
Finished!
2) Second approach would be to poll for CurrentCharacter. Note that it also requires you to halt execution by using pause / drawnow for the character stroke to be processed. A side-effect of this approach is that after a key press the focus moves to command window, and the character also appears there.
function test()
hFig = figure();
set(hFig, 'CurrentCharacter', '^'); % some other character
drawnow();
while true
A = randn(10000); % doing some stuff
pause(0.01);
char = get(hFig, 'CurrentCharacter');
if strcmp(char, ' ')
break;
end
fprintf('Still running...\n');
end
fprintf('Finished!\n');
end
EDIT elaborating on the threading in Matlab:
Matlab GUI components actually run on EDT thread, which is separate to the one where the main execution is happening (unless you create java GUI objects explicitly without using javaObjectEDT, which you should avoid) - this is what allows GUI components to visually react on some actions you take which do not require synchronization with the main execution thread, like visually changing button state when clicking on it. But to actually get the callback to run and change the state of your workspace inside the execution thread, you need to let Matlab synchronize the two threads. This is what pause/drawnow helps to do - it halts whatever you've been doing on the execution thread which allows your GUI callbacks to execute in the meantime. drawnow would clear the whole pending queue before returning execution to your original code block, while pause will potentially only process some of the callbacks until the time runs out. You may observe this if you set pause argument to a tiny fraction of a second and make lots of actions - not all will be processed.
You may notice some slight changes in behavior between different Matlab releases - the two threads seem to become slightly more independent over time. There is surprisingly little official information available on this - most of it is based on experience and various answers scattered across Matlab central, like this and that, and obviously fantastic articles on the UndocumentMatlab, like the one linked above.
Why not something like that:
ended = false
while !ended
if pressed_spacebar
ended = true
If you can't change your loop condition, you can use the break instruction but it's not a good programming practise :)

Stop A GUI in a middle of process in MATLAB

I'm designing a GUI using GUIDE in MATLAB R2014b. My program has a long loop (takes 2~5h to process). I want have a button in my GUI that the user stop the process every time he/she want (The GUI is updating graphs and texts continuously based on result of loops). Something like pressing Control+C not after ending a loop. How can I implement this?
PS.
I don't want MATLAB remove my workspace. The user can continue the process with previous loaded data and workspace by changing some options in GUI.
Here is a trick that should work: Somewhere in the GUI, like in its OpeningFcn for instance, initialize a flag named for example StopNow to false and store it in the handles structure of the GUI. Then in the loop that takes long to execute, put an if statement with a call to return whenever the flag is set to true. That will stop the execution of the loop and you will have access to your data. You can make a pushbutton to change the flag value.
Sample code: I made a simple GUI that starts enumerating digits in a for loop and printing them in a text box. When you press the STOP button, the flag is set to true and the loop stops. If something is unclear please tell me.
function StopGUI
clear
clc
close all
%// Create figure and uielements
handles.fig = figure('Position',[440 500 400 150]);
handles.CalcButton = uicontrol('Style','Pushbutton','Position',[60 70 80 40],'String','Calculate','Callback',#CalculateCallback);
handles.StopButton = uicontrol('Style','Pushbutton','Position',[250 70 80 40],'String','STOP','Callback',#StopCallback);
%// Initialize flag
handles.StopNow = false;
handles.Val1Text = uicontrol('Style','Text','Position',[150 100 60 20],'String','Value 1');
handles.Val1Edit = uicontrol('Style','Edit','Position',[150 70 60 20],'String','');
guidata(handles.fig,handles); %// Save handles structure of GUI. IMPORTANT
function CalculateCallback(~,~)
%// Retrieve elements from handles structure.
handles = guidata(handles.fig);
for k = 1:1000
if handles.StopNow == false
set(handles.Val1Edit,'String',num2str(k));
pause(.5) %// The pause is just so we see the numbers changing in the text box.
else
msgbox('Process stopped');
return
end
end
guidata(handles.fig,handles); %// Save handles structure of GUI.
end
function StopCallback(~,~)
%// Retrieve elements from handles structure.
handles = guidata(handles.fig);
handles.StopNow = true;
guidata(handles.fig,handles); %// Save handles structure of GUI.
end
end
Screenshot after pressing the STOP button:
Hope that helps!
Best solution would be to use separate threads (one for the user interface and one for the processing) maybe using parallel toolbox. Anyhow this would be then quite complex to synchronise both.
So, here is a simple solution that only relies on anonymous functions (to delegate interface refreshing outside the processing block) and on drawnow function (to force the graphical interface to process its messages).
Sample application
The sample application to work with is very basic. It contains:
A settings panel (with only one setting, the number of iterations for the processing block)
A progress bar
A Go/Cancel button
NB: Source code is quite long (about 250 lines, mainly due to gui creation), so I dropped it here.
GUI creation is not important. The most important parts are the processing block, the anonymous functions to instrument the code and the callbacks to react to the GUI events. I will thus detail theses only.
The processing block
Processing block is a simple routine:
function [] = processing(count, instrumentation)
%[
for ki = 1:count,
instrumentation.CheckCancel();
instrumentation.Progress((ki-1)/count);
if (ki > 1), pause(1); end
instrumentation.CheckCancel();
instrumentation.Progress(ki/count);
end
%]
end
The only special thing about it is that it takes an additional instrumentation structure. This structure has two fields that points to two anonymous functions defined by the caller (i.e. the graphical interface). We'll see shortly how.
CheckCancel is a function in charge of raising an error if the user wants to stop the processing.
Progress is a function on which to delegate progression report.
Here is how the anonymous functions are connected to the graphical interface (see doProcessing sub-function in the code):
% Connect instrumentation callbacks with the gui
instrumentation.CheckCancel = #(ratio)onCheckCancel(dlg);
instrumentation.Progress = #(ratio)onProgress(dlg, ratio);
% Perform the processing
processing(settings.NumberOfIterations, instrumentation);
Progress and CheckCancel handlers
Here is the handler defined by the GUI for Progress:
function [] = onProgress(dlg, ratio)
%[
% Update the progress bar value
data = guidata(dlg);
uiprogress(data.handles.pbProgress, ratio);
% Force interface to refresh
drawnow();
%]
end
This is simple, it just updates progressbar control and forces the GUI to refresh (remind that matlab is single-threaded and is currently executing the processing block, so we need to force GUI refreshing).
Here is the handler for CheckCancel:
function [] = onCheckCancel(dlg)
%[
% Force interface to process its events
drawnow();
% Check 'UserData' has not been modified during events processing
guiState = get(dlg, 'UserData');
if (~isempty(guiState) && ....
strcmp(guiState, 'CancelRequested') || strcmp(guiState, 'CloseRequested'))
error('System:OperationCanceledException', 'Operation canceled');
end
%]
end
Again, this is quite simple. We force the GUI to process events (buttons clicks, etc...) and then we read if UserData was modified to some expected value. If so, we raise an exception to stop the processing. Remind again that currently executing code is the processing block.
GUI events handlers
The GUI has only two interesting events. Either the user clicks the close button, either he/she clicks the Go/Cancel button.
NB: Remind that even if matlab is locked in executing the processing block, GUI events are still processed because processing block is calling drawnow from time to time (by the mean of the instrumentation delegates).
Here is the code for the close button:
function [] = onCloseRequest(dlg)
%[
% If already in computation mode
if (~isempty(get(dlg, 'UserData')))
% Just indicate close is requested and leave immediatly
set(dlg, 'UserData', 'CloseRequested');
data = guidata(dlg);
set(data.handles.btnGoCancel, 'Enable', 'off', 'String', 'Cancelling...');
return;
end
% Immediate close
delete(dlg);
%]
end
This is simple, if we are in running mode, we just signal we want to stop, else we close the dialog immediately.
Here is the code for the go/cancel button:
function [] = onGoCancelClick(dlg)
%[
% If already in computation mode
if (~isempty(get(dlg, 'UserData')))
% Just indicate cancel is requested and leave immediatly
set(dlg, 'UserData', 'CancelRequested');
data = guidata(dlg);
set(data.handles.btnGoCancel, 'Enable', 'off', 'String', 'Cancelling...');
return;
end
% Go into computation mode
[settings, err] = tryReadSettings(dlg);
if (~isempty(err))
waitfor(msgbox(err.message, 'Invalid settings', 'Error', 'Modal'));
else
enterComputationMode(dlg);
err = doProcessing(dlg, settings);
leaveComputationMode(dlg, err);
end
%]
end
It's a little longer, anyhow this is the same. If we're in running mode, we just indicate we want to stop; else, the interface is in normal mode, and we start the processing.
Functions tryReadSettings, enterComputationMode and leaveComputationMode are just glue to update controls in the interface and nicely report for errors or cancellation.
Conclusion
We have designed a responsive graphical interface relying only on drawnow and anonymous functions. This is of course just a trick and a better solution would be to use multitasking.
The graphical interface was created here programmatically. Principle is the same if build with GUIDE or with the help of the GUI Layout toolbox.
Instrumentation callbacks can further be improved, for instance, by adding a Log field to report processing details in a textbox or to some back-end similar to Log4Net (with just a message level and message value). Or by adding callback for intermediate results.
Interface can also be improved or modified, for instance why not to run processing whenever a setting is modified (i.e. just stopping any current run and without the need to manually click on a 'Go/Cancel' button each time).
There are a lot of possibilities. Here, just providing some ground application to start with (or not ...).

Matlab gui WindowButtonMotionFcn crashes when called too often?

I've set WindowButtonMotionFcn to my callback which plots three plots, with the data depending on mouse position. However this seems to be too much for MATLAB to handle, because after moving my mouse around a bit, the GUI stops responding.
I use this code (copied parts from someone):
set(handles.figure1, 'windowbuttonmotionfcn', #hover_Callback);
function hover_Callback(hObject, handles, eventdata)
inside = false;
pos = get(handles.axes1, 'currentpoint');
xlim = get(handles.axes1, 'XLim');
ylim = get(handles.axes1, 'YLim');
if (pos(1,1) > max(xlim(1), 1) && ...
pos(1,1) < xlim(2) && ...
pos(1,2) > ylim(1) && ...
pos(1,2) < ylim(2))
inside = true;
end
if ~inside
return
end
ix = round(pos(1,1));
iy = round(pos(2,2));
axes(handles.axes2); cla; plot(squeeze(t2(ix,iy,:)), squeeze(d2(ix,iy,:)));
axes(handles.axes3); cla; plot(squeeze(t3(ix,iy,:)), squeeze(d3(ix,iy,:)));
axes(handles.axes4); cla; plot(squeeze(t4(ix,iy,:)), squeeze(d4(ix,iy,:)));
This causes my GUI to stop responding, without error codes. If I then quit it and start it again the whole of MATLAB stops responding. Anyone knows what could be happening and how I can fix this? Maybe I'm somehow clogging my memory?
When a callback is called with high frequency, there is the danger that it will be called again before another call has finished executing (i.e. re-entrancy). With WindowButtonMotionFcn, there's a pretty darn good chance that this will happen.
You can prevent callback re-entrancy by inspecting the function call stack (the output of dbstack) for multiple calls to the responsible callback. A very straightforward, but clever implementation of such a check called isMultipleCall is presented in a post on undocumentedmatlab.com. The idea is to count the number of times the callback function name appears on the stack. Take the actual function directly from undocumentedmatlab.com, but it distills to the following:
function flag=isMultipleCall()
s = dbstack();
% s(1) corresponds to isMultipleCall
if numel(s)<=2, flag=false; return; end
% compare all functions on stack to name of caller
count = sum(strcmp(s(2).name,{s(:).name}));
% is caller re-entrant?
if count>1, flag=true; else flag=false; end
The usage of isMultipleCall is very simple. Put run it at the top of the callback (in this case, hover_Callback), and bail out if it indicates that multiple calls are in progress:
function hover_Callback(hObject, eventdata, handles)
if isMultipleCall(); return; end
...
end
This prevents the callback from executing fully again until previous calls have terminated. Only the check will be run, skipping the intensive graphics object operations (i.e. axes, plot, etc.)
An alternative approach is to use a listener for the WindowButtonMotionEvent:
handles.motion = handle.listener(gcf,'WindowButtonMotionEvent',#hover_callback2);
Then in the callback, check the eventdata.CurrentPoint property instead of currentpoint. Check for re-entrancy as above.
If you are NOT using GUIDE and do not have a handles structure managed by guidata, then call the listener something like motionListener and use setappdata to store the listener. For example,
setappdata(hFigure,'mouseMotion',motionListener);
Just use the known handle of any object in the GUI so the listener persists. You could also use UserData instead of setappdata, or any other way of managing GUI data.
As an aside, note that the axes command is rather slow, and can be avoided by passing the axis handle to plot directly:
plot(handles.axes2, squeeze(t2(ix,iy,:)), squeeze(d2(ix,iy,:)));

How to specify when to return output of the function

Say I have the following function:
function result=myfun(varargin)
result=[];
myFig=figure();
B1=uicontrol(myFig,'Style','pushbutton','String','done','Callback',{#done_Callback});
function done_Callback(varargin)
result =10;
delete(mainFig);
end
end
I am trying to only return output after the button callback is executed. Right now it returns an empty variable right away. I know how to do this in guide GUIs but all of my project is written without guide. I am assuming I need uiwait somewhere, but not sure where.
The function uicontrol only generates the button, it doesn't wait for it to be pressed. Otherwise, a full GUI with several elements would not be possible – you couldn't insert another element before the first hadn't been activated, and afterwards the first one could not be activated any longer. For this reason, GUI callbacks are executed in another thread than the main Matlab program, namely in the "event queue".
If you want your program to wait until the button is pressed, you have to program this explicitly:
function result=myfun(varargin)
result=[];
myFig=figure();
B1=uicontrol(myFig,'Style','pushbutton','String','done','Callback',{#done_Callback});
while isempty(result)
drawnow
end
function done_Callback(varargin)
result =10;
fprintf('hi\n')
delete(myFig);
end
end
The drawnow is there to tell Matlab it should allocate execution time to the event queue, which is not normally done when Matlab is busy, e.g. with running a while loop.
For (slightly) more information, have a look at How Does a GUI Work? and drawnow.

How to prevent a callback from being interrupted by a figure's close function?

Was wondering how the question in the title can be achieved. I have some callbacks that run from button presses. These callbacks, if interrupted by the figure close, will cause errors because the function seems to run, then gets interrupted by the close function which closes the figure, and then the callback seems to resume after the figure is closed.
If I set the button's 'Interruptible' property to 'on', it prevents other callbacks from interrupting it, but does not seem to work for the figure's close function. Another idea I had was to specify the 'closefunction' in the figuring's 'CloseRequestFcn' callback and then call drawnow to flush the eventqueue before deleting the figure but this did not work.
The last resort for me is to simply set the figure's 'CloseRequestFcn' to '' when running callbacks but this seems tedious. Is there a standard solution to accomplish this?
EDIT:
From matlab's documentation:
Note If the interrupting callback is a DeleteFcn or CreateFcn
callback or a figure's CloseRequest or ResizeFcn callback, it
interrupts an executing callback regardless of the value of that
object's Interruptible property. The interrupting callback starts
execution at the next drawnow, figure, getframe, pause, or waitfor
statement. A figure's WindowButtonDownFcn callback routine, or an
object's ButtonDownFcn or Callback routine are processed according to
the rules described above.
So it appears to be the case that the interruptible property doesn't effect the close function.
EDIT 2:
Ok, so I think I found a problem. It's really bizarre. I actually discovered from the matlab documentation that callbacks are only interruptible if they have the interruptible property set to on AND :
If there is a drawnow, figure, getframe, waitfor, or pause command in the running callback, then MATLAB executes the interrupting callbacks which are already in the queue and returns to finish execution of the current callback.
I don't use any of these functions explicitly, so it turns out most of my callbacks aren't interruptible by the closereqfcn. BUT, it turns out some are, and the reasons why seem very strange. If have a callback with:
`large computation -> imshow -> imshow
large computation -> set -> set -> set -> set
where the set command is setting the axes visible property to off, then no interruption seems to occur if I exit during the callback
Now, if I have:
large computation -> imshow -> set -> imshow -> set
matlab issues an error if I exit during the callback on the second set command. Also, if I have:
large computation -> imshow -> imshow -> set
matlab issues an error if I exit during the callback on the first set command.
large computation -> imshow -> imshow -> imshow
also issues an error on the third imshow if I cancel during the callback.
For some reason it seems that two successive calls to imshow makes my callback interruptible. Is it possible matlab implicitly calls drawnow or does something weird if you use multiple imshows? BTW, my matlab version is R2009a.
I never really trusted that Interruptible flag (or comparable mechanisms)...I immediately admit I have never used it a lot, but that was because when I was experimenting with it for the first time, I noticed that 'Interruptible', 'off' (and friends) seemed to have more exceptions to the rule than vindications of it -- headache material alert!
So, I got in the habit of tackling this sort of problem simply by using flags, and wrapping all callbacks that must really be uninterruptible in a locking/releasing function.
Something like this:
% Define a button
uicontrol(...
'style', 'pushbutton',...
'interruptible', 'off',... % Nice, but doesn't catch DeleteFcn, CreateFcn, ...
% CloseRequestFcn or ResizeFcn
% ...
% further definition of button
% ...
% Put callback in a wrapper:
'callback', #(src,evt) uninterruptibleCallback(#buttonCallback, src,evt)...
);
where uninterruptibleCallback() looks something like this:
function varargout = uninterruptibleCallback(callback, varargin)
% only execute callback when 'idle'
% (you can omit this if you don't want such strict ordering of callbacks)
while ~strcmp( get(mainFigure, 'userData'), 'idle' )
pause(0.01);
% ...or some other action you desire
end
% LOCK
set(mainFigure, 'userData', 'busy');
try
% call the "real" callback
[varargout{:}] = callback(varargin{:});
% UNLOCK
set(mainFigure, 'userData', 'idle');
catch ME
% UNLOCK
set(mainFigure, 'userData', 'idle');
throw(ME);
end
end
Which allows you to use this closeReqFcn() for your figure:
function closeReqFcn(~,~)
% only when the currently running locked callback (if any) has finished
while ~strcmp( get(mainFigure, 'userData'), 'idle' )
pause(0.01);
% ...or some other action you desire
end
% ...
% further clean-up tasks
% ...
% deletion
delete(mainFigure);
end
Theoretically, when you put all callbacks in this sort of schema, it is basically equal to managing your own event queue.
This of course has a few advantages, but many, many drawbacks -- you might want to think this through for a bit. This whole mechanism might be unacceptably slow for your use case, or you might need to define a few more locking functions with far more specific behavior.
In any case, I suspect it's a good place to start off from.
An alternative to #Rody Oldenhuis's solution is to start a timer inside the CloseRequestFcn to close the figure when no uninterruptible code is in progress (which could be indicated by a flag; Closing_Allowed).
function mainFig_CloseRequestFcn(hObject, eventdata, handles)
Time = 3; % Wait time before force killing (in sec)
Kill.tmr = timer('executionMode', 'fixedRate',...
'Period', 1/10,...
'TimerFcn', {#KillingTimer_Callback, handles});
Kill.counts = ceil(Time/Kill.tmr.Period);
setappdata(handles.mainFig,'Kill',Kill);
start(Kill.tmr);
function KillingTimer_Callback(hObject, eventdata, handles)
Kill = getappdata(handles.mainFig,'Kill');
Kill.counts = Kill.counts - 1; % Count down
setappdata(handles.mainFig,'Kill',Kill);
if Kill.counts == 0 || getappdata(handles.mainFig, 'Closing_Allowed')
stop(Kill.tmr);
delete(handles.mainFig);
end
if Kill.counts == 0 means time out, and closes the figure even if an uninterruptible task is in progress, which then would result in the same errors you get sometimes now, but if you know the maximum amount of time you need to finish the uninterruptible jobs, then you can set the Time above properly.
Finally wrap the uninterruptible code by setting the Closing_Allowed flag.
function pushbutton_Callback(hObject, eventdata, handles)
setappdata(handles.mainFig, 'Closing_Allowed', 0); % Closing is not allowed
pause(2);
setappdata(handles.mainFig, 'Closing_Allowed', 1); % Closing is allowed