Real time audio processing possible with App Designer in Matlab? - matlab

I want to code an easy audio filter app using the App Designer in Matlab. One should be able to load an audio file, press play and change parameters like input gain, cutoff frequency etc. while the file is being played.
I just cannot wrap my head around how to make it possible to change the parameters in realtime and update the corresponding variables so that one can hear how the filter is changing.
This is the code I have written by now:
classdef EulerFilter < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
CutoffKnobLabel matlab.ui.control.Label
CutoffKnob matlab.ui.control.Knob
PlayButton matlab.ui.control.StateButton
end
properties (Access = public)
inputGain % input Gain
CutoffHz % cutoff frequency in Hz
end
methods (Access = public)
function play(app)
% setup file stream
frameLength = 256;
fileReader = dsp.AudioFileReader(...
'Sun Behind CloudsDry.wav',...
'SamplesPerFrame',frameLength);
deviceWriter = audioDeviceWriter(...
'SampleRate',fileReader.SampleRate);
% code snippet
% porcessing of frames
while ~isDone(fileReader)
% code snippet
end
release(fileReader);
release(deviceWriter);
end
end
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
app.inputGain = 1;
app.CutoffHz = 22000;
end
% Value changed function: PlayButton
function PlayButtonValueChanged(app, event)
value = app.PlayButton.Value;
play(app);
end
% Value changing function: CutoffKnob
function CutoffKnobValueChanging(app, event)
%display(event)
changingValue = event.Value;
app.CutoffHz = changingValue;
end
end
% App initialization and construction
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure
app.UIFigure = uifigure;
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = 'UI Figure';
% Create CutoffKnobLabel
app.CutoffKnobLabel = uilabel(app.UIFigure);
app.CutoffKnobLabel.HorizontalAlignment = 'center';
app.CutoffKnobLabel.Position = [159 322 37 22];
app.CutoffKnobLabel.Text = 'Cutoff';
% Create CutoffKnob
app.CutoffKnob = uiknob(app.UIFigure, 'continuous');
app.CutoffKnob.Limits = [10 22000];
app.CutoffKnob.MajorTicks = [10 1000 5000 22000];
app.CutoffKnob.ValueChangingFcn = createCallbackFcn(app, #CutoffKnobValueChanging, true);
app.CutoffKnob.Position = [155 367 45 45];
app.CutoffKnob.Value = 22000;
% Create PlayButton
app.PlayButton = uibutton(app.UIFigure, 'state');
app.PlayButton.ValueChangedFcn = createCallbackFcn(app, #PlayButtonValueChanged, true);
app.PlayButton.Text = 'Play';
app.PlayButton.Position = [60 40 100 22];
end
end
methods (Access = public)
% Construct app
function app = EulerFilter
% Create and configure components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, #startupFcn)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
It is mostly the functions Matlab has generated for the GUI. I have added some properties which hold the values for input gain, cutoff etc. as well as the play() function which performs the signal processing.
I can run the app, press the play button and hear the audio file being played, but when I change the cutoff frequency for example, nothing changes. I guess this is because I execute the play() function inside the callback function when the play button was pressed and thus the callback functions when the cutoff knob is turned cannot be executed before the other one has finished.
When I first change the parameters and then press play, everything is correct except that I cannot change the parameters while the file is playing.
I have tried the following without success:
calling the callback function inside the while loop in the play() function, but I don't know what argument I have to pass for event (Matlab always tells me that it doesn't know the command or arguments are missing) or if this is even useful
execute the play() function inside the runStartupFcn() but this function is executed before the GUI is shown which is useless of course
I cannot add functions elsewhere as far as I can tell
So now the question is: Can I make the app work in realtime?
I am looking forward to your answers!

I think that the solution to your problem is creating a second thread. In Your main thread you have access to your handles and variables and your second thread runs the sound. My idea would have been including the changes that you do in thread A to thread B. Unaffortunately you can just use multithreading with the MatLab Parallel Processing Toolbox. I hope there is another way though.
Cheers, Pablo

There seem to be a lot of solutions/examples for Matlab's guide but not yet for the app designer.
It looks like your best bet is to call a pause function in the while loop to give your program time to get the updated values. Experiment with different pause times to make sure your program has enough time to update. Matlab can pause the current executing thread by using :
pause(0.001) % 0.001 sec
Or do a direct call to Java for more accuracy
java.lang.Thread.sleep(duration) % duration in msec
I'm pretty sure this will give your program the time to access the variables and update. This way you could check every 10/20/50/1000 loop cycles and update the parameters as often as you'd like to minimize any audible artifacts.
% Init counter to see how many loops have passed
counter = 0;
% processing of frames
while ~isDone(fileReader)
% Do your playback process stuff
if(counter > 10) % Updates every 10 loops or so
pause(0.001);
counter = 0;
end
counter = counter + 1;
end
Note: Code not tested, please let me know
Otherwise maybe have a look at a callback approach solution.
This is why GUIs in Matlab aren't always such a good idea :-) I understand why you might be doing this for a learning purpose but otherwise I would maybe investigate more integration with Java into your Matlab GUI's to handle all of the threading (or even the GUI design with Java itself). To get started...

May be too late to the thread to be of help, but the problem you're running into is when CALLBACK1 is invoked, it calls your PLAY() function, which does not run to completion until your file reading WHILE loop is complete. In other words, CALLBACK1 never finishes running until your file reading is complete.
If you change the cutoff frequency while CALLBACK1 is still reading the file, it (I assume) is calling its own callback, I'll refer to as CALLBACK2. Since MATLAB is single threaded, CALLBACK2 can't run until CALLBACK1 finishes running. Hence why you run into the issue you have.
The way to handle this is for CALLBACK1 to start a MATLAB TIMER object, and configure the timer object (which runs in a separate thread) to read the file at some frequency. This way, CALLBACK1 finishes running pretty quickly, while the timer object does your playing. This allows CALLBACK2 to execute and do its thing.
The complication you may still run into is whether you can change the cutoff frequency "on the fly" for the "playing" to reflect it. That's more a question whether the AudioFileReader object allows that.
Hope this helps.

Related

Boost refresh rate of App Designer UI elements

I am currently trying to display data that I receive via serial port in a Matlab app designer application. I am suffering from abysmal refresh rate of the linear gauges (~1 Hz).
The gauges' values are updated by a fixed-rate timer which is set to 30Hz.
A timestamp print in the timer callback shows me that it is called with the correct frequency. My computer is quite beefy and the Task Manager doesn't show any hints of high load - in fact, the MATLAB app consumes almost no CPU time at all. It's actually not just the gauges but all UI elements.
So my guess - or better: my hope - is that there must be some hard cap on the refresh rate. The official documentation doesn't give any hints about how to change this, though.
My MATLAB version is R2016b.
So my question(s):
Is this fixed with R2017a?
If not: can I do something about it, i.e. fiddling with MATLAB builtin files?
Here's a MCV example demonstrating the issue:
classdef testapp < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
andwatchhowthisstartstospinsmoothlyGaugeLabel matlab.ui.control.Label
andwatchhowthisstartstospinsmoothlyGauge matlab.ui.control.SemicircularGauge
KeepturninghereKnobLabel matlab.ui.control.Label
KeepturninghereKnob matlab.ui.control.Knob
end
properties (Access = private)
tim_the_timer
i = 0;
end
methods (Access = private)
function app = refreshMeter(app, ~,~)
% display timestamp
datestr(now,'HH:MM:SS.FFF')
% update the gauge
app.andwatchhowthisstartstospinsmoothlyGauge.Value = app.i;
app.i = app.i + 1;
if app.i > 100
app.i = 0;
end
end
end
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
t = timer;
t.TimerFcn = #app.refreshMeter;
t.Period = 0.02;
t.BusyMode = 'drop';
t.ExecutionMode = 'fixedRate';
start(t);
app.tim_the_timer = t;
end
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
stop(app.tim_the_timer);
delete(app.tim_the_timer);
delete(app);
end
end
% App initialization and construction
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure
app.UIFigure = uifigure;
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = 'UI Figure';
app.UIFigure.CloseRequestFcn = createCallbackFcn(app, #UIFigureCloseRequest, true);
setAutoResize(app, app.UIFigure, true)
% Create andwatchhowthisstartstospinsmoothlyGaugeLabel
app.andwatchhowthisstartstospinsmoothlyGaugeLabel = uilabel(app.UIFigure);
app.andwatchhowthisstartstospinsmoothlyGaugeLabel.HorizontalAlignment = 'center';
app.andwatchhowthisstartstospinsmoothlyGaugeLabel.Position = [275 138 246 15];
app.andwatchhowthisstartstospinsmoothlyGaugeLabel.Text = '... and watch how this starts to spin smoothly';
% Create andwatchhowthisstartstospinsmoothlyGauge
app.andwatchhowthisstartstospinsmoothlyGauge = uigauge(app.UIFigure, 'semicircular');
app.andwatchhowthisstartstospinsmoothlyGauge.Position = [338 168 120 65];
% Create KeepturninghereKnobLabel
app.KeepturninghereKnobLabel = uilabel(app.UIFigure);
app.KeepturninghereKnobLabel.HorizontalAlignment = 'center';
app.KeepturninghereKnobLabel.Position = [119 265 112 15];
app.KeepturninghereKnobLabel.Text = 'Keep turning here...';
% Create KeepturninghereKnob
app.KeepturninghereKnob = uiknob(app.UIFigure, 'continuous');
app.KeepturninghereKnob.Position = [145 314 60 60];
end
end
methods (Access = public)
% Construct app
function app = testapp()
% Create and configure components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, #startupFcn)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
Edit: I noticed that the gauge gets immediately updated when I turn a knob, slider, etc. So somehow the capability of a higher refresh rate is definitely there... but how to enable it without having to touch controls? Updated MCV accordingly.
You should be able to force a refresh by calling the drawnow function in the refreshMeter callback.
I would suggest the following things to help with your problem:
follow this very useful link which provides mathworks solution for low-level graphics issues. It may have to do with your graphics card.
following #MrAzzamans suggestion, drawnow and refreshdata could help solve your problem (keep in mind they have different summoning options).
If you're using GUIDE, try changing to App Designer and see if it solves your problem.
Iv'e encountered similar problems when building a "video-player" in GUIDE, the first suggestion fixed it for me.
So i got in touch with MathWorks support regarding this issue. Unfortunately, this seems to be a known issue prevalent in both R2016b and 2017a that might be fixed in future releases. Support couldn't provide me with a workaround either, so for the time being i just print the measurement data to the matlab command line.
I found a way to force events triggering an update for a widget, for which drawnow was inoperate: try a sendkeys with a carriage return:
h = actxserver('WScript.shell');
h.SendKeys(newline);

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 ...).

Showing data on Matlab GUI which is continuously being updated in a separate Matlab function

I have a function in Matlab which is getting continuous sensor values from a hardware. It gives a flag when new values are available and we can update the variables holding these values. Following is a dummy function to mimic what this function is doing.
function example( )
% Example function to describe functionality of NatNetOptiTrack
% Hardware initialization,
% Retriving real time information continuously
for i = 1:100 %in real time this loop runs for ever
data = rand(3,6);
% Send the updated data to gui in each iteration
end
end
i have made a gui using guide as shown in the figure:
So the data to be displayed is a 3x6 matrix with columns corresponding to X Y Z Roll Pitch and Yaw values while rows correspond to Objects.
I want to show the continuously updated values from this function on the gui. Is there a way i can initialize gui inside my example function and update the output value by using the handles inside my loop. I tried copying the gui code inside the example function as a script, it was able to initialize but was not recognizing the handles.
Also i want to show the current values on command window when i press the button.
Thanks
If you launch the GUI and then run the function, you should be able to get the handles to the controls on the GUI provided that you make the GUI figure handle visible and set its tag/name to something appropriate. In GUIDE, open the Property Inspector for the GUI and set the HandleVisibility property to on, and the Tag property to MyGui (or some other name). Then in your example.m file do the following
function example( )
% Example function to describe functionality of NatNetOptiTrack
% get the handle of the GUI
hGui = findobj('Tag','MyGui');
if ~isempty(hGui)
% get the handles to the controls of the GUI
handles = guidata(hGui);
else
handles = [];
end
% Hardware initialization,
% Retriving real time information continuously
for i = 1:100 %in real time this loop runs for ever
data = rand(3,6);
% update the GUI controls
if ~isempty(handles)
% update the controls
% set(handles.yaw,…);
% etc.
end
% make sure that the GUI is refreshed with new content
drawnow();
end
end
An alternative is to copy the example function code into your GUI - the hardware initializations could occur in the _OpeningFcn of your GUI and you could create a (periodic) timer to communicate with the hardware and get the data to display on the GUI.
As for displaying the current data when pressing the GUI button, you can easily do this by writing the contents of the GUI controls to the command line/window with fprintf. You will though need to make your example function interruptible so that the push button can interrupt that continuously running loop. You can do this by either adding a pause call (for a certain number of milliseconds) that gets executed at the end of each iteration of your loop, or just make use of the drawnow call from above (that is why I placed it outside of the if statement - so that it will be called on each iteration of your loop.
Try the above and see what happens!

pass value between two callback function in matlab GUI

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

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,:)));