Forcing slider values to round to a valid number

9 次查看(过去 30 天)
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 个评论
Caleb
Caleb 2012-8-10
I figured it out. I don't know why I was struggling with it.
slidervalue = (round(slidervalue/3))*3

请先登录,再进行评论。

回答(2 个)

Sam Butler
Sam Butler 2013-4-11
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 2012-8-10
There's probably a better way but:
x = 10.5;
vm = 3;
y = 0:vm:(x+vm);
[~,idx] = min(abs(x-y));
y(idx)

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by