Forcing slider values to round to a valid number

11 views (last 30 days)
For many of the functions that I've programmed to be adjustable using sliders, I have to use integer values. It's easy to program the minor and major step of the sliders to make sure that there won't be an error with the value.
However, when the user decides to drag the slider and move it to any position they desire, it will inevitably not land on an integer value. I have used ceil() to round the value up for functions which values must be non-negative integers. But for functions in which a parameter must be a non-negative multiple of some integer, I don't know how to force the slider to move from an invalid number to the next highest valid number.
For example: the slider value must be a non-negative multiple of 3. The user drags the slider and drops it on 10.5. If I use ceil(), the value will be rounded to 11, which is no more valid an entry than 10.5. How do I get the slider to round to 9 or 12?
  1 Comment
Caleb
Caleb on 10 Aug 2012
I figured it out. I don't know why I was struggling with it.
slidervalue = (round(slidervalue/3))*3

Sign in to comment.

Answers (2)

Sam Butler
Sam Butler on 11 Apr 2013
If you want to update the slider to have this new value as well, be sure that after you do the rounding, you also use:
set(hObject, 'Value', slidervalue);
Without this, the slider will still be resting on a floating point value (so it may not look right to the user).

Sean de Wolski
Sean de Wolski on 10 Aug 2012
There's probably a better way but:
x = 10.5;
vm = 3;
y = 0:vm:(x+vm);
[~,idx] = min(abs(x-y));
y(idx)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!