10

I have created a MATLAB GUI using GUIDE. I have a slider with a callback function. I have noticed that this callback, which is supposed to execute 'on slider movement', in fact only runs once the slider has been moved and the mouse released.

Is there a way to get a script to run as the slider is being dragged, for live updating of a plot? There would I presume need to be something to stop the script being run too many times.

Jonas Heidelberg
  • 4,984
  • 1
  • 27
  • 41
Bill Cheatham
  • 11,396
  • 17
  • 69
  • 104

3 Answers3

16

Even though the callback of the slider isn't being called as the mouse is moved, the 'Value' property of the slider uicontrol is being updated. Therefore, you could create a listener using addlistener that will execute a given callback when the 'Value' property changes. Here's an example:

hSlider = uicontrol('Style', 'slider', 'Callback', @(s, e) disp('hello'));
hListener = addlistener(hSlider, 'Value', 'PostSet', @(s, e) disp('hi'));

As you move the slider you should see 'hi' being printed to the screen (the listener callback), and when you release the mouse you will see 'hello' printed (the uicontrol callback).

gnovice
  • 125,304
  • 15
  • 256
  • 359
  • Thanks, this example basically does what I want to do. I have one question though; what does the `@(s, e)` do before the `disp` function? I guess the `@` creates the handle to disp, but what is the `(s, e)`? – Bill Cheatham May 18 '11 at 09:24
  • 2
    @Bill: The `@(s,e)` creates an [anonymous function](http://www.mathworks.com/help/techdoc/matlab_prog/f4-70115.html) that takes as input arguments `s` and `e` and executes `disp(...)`. Using [function handles as callbacks](http://www.mathworks.com/help/techdoc/creating_guis/f16-999606.html#f16-1001315) requires that the function accepts at least two arguments, even if they aren't used. These arguments are the handle of the object issuing the callback (`s`) and the event data it optionally provides (`e`). More descriptive names would be `hObject` and `eventData`, but I was keeping things short. – gnovice May 18 '11 at 13:52
4

Just for the record, this subject is discussed in detail here: http://UndocumentedMatlab.com/blog/continuous-slider-callback/ - several alternative solutions are presented there. gnovice's solution using addlistener is equivalent to the handle.listener alternative, since addlistener is basically just a wrapper for the latter.

Yair Altman
  • 5,704
  • 31
  • 34
0

If you want to execute the same original callback you passed to uicontrol you can add this generic listener which bootstraps the existing callback:

sld.addlistener('Value','PostSet',@(src,data) data.AffectedObject.Callback(data.AffectedObject,struct('Source',data.AffectedObject,'EventName','Action')));

Related blog post

Alec Jacobson
  • 6,032
  • 5
  • 51
  • 88