Continuous Slider in Matlab

Alec Jacobson

October 15, 2014

weblog/

Here's the typical way to create a slider in matlab:

sld = uicontrol('Style', 'slider','UserData',10,'Callback',@(src,data) disp(src.UserData * src.Value));

The callback here is boring but shows how to use 'UserData' to pass information to the callback: here, it's just multiplying the slider's current value by 10 and displaying the result.

However, the callback only triggers on the mouse up event. This is rather unsatisfying. To fix this, add this generic listener to the slider, which bootstraps the current callback:

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

Now, the callback is firing on the mouse drag events. It's generic in the since that you shouldn't need to change this line if you used a different callback. It will even continue to work if you change the callback during interaction.

I'm aping the data parameter in the uicontrol callback with a simple struct. I'm not really sure what this data parameter is good for anyway.