Clear Filters
Clear Filters

How do I set slider step value in Matlab?

63 views (last 30 days)
Ahmad
Ahmad on 31 Dec 2023
Commented: Voss on 31 Dec 2023
I am using a slider and I've set it's maximum value to +12 and minimum value to -12. I want that with every click on slider and arrow, it should increment/decrement the value of slider by 1. I've tried this code. Apparently, it should give me a total of 25 steps from +12 to -12 but it is giving me 26 steps. Also, how can I display the current value of slider using static text?
The code is given below:
function slider1_Callback(hObject, eventdata, handles)
set(handles.slider1,'min',-12);
set(handles.slider1,'max',12);
set(handles.slider1,'SliderStep',[0.04,0.04]);
end

Accepted Answer

Voss
Voss on 31 Dec 2023
Edited: Voss on 31 Dec 2023
SliderStep = 0.04 gives you 26 steps because the change in the slider's value from one click is
(Max-Min)*SliderStep = (12-(-12))*0.04 = 0.96
So it takes 24/0.96=25 clicks to go from min value to max value. (Note that there is one more step by your counting because you are counting the number of states the slider is in as you click from min value to max value, and I am counting the number of clicks in between min and max.)
Note that 25=1/0.04, i.e., the number of clicks from min to max is the inverse of the SliderStep. Therefore, in order to have each click change the slider value by 1, you want it to take 24 clicks to go from min to max, which means the sliderStep should be 1/24.
set(handles.slider1,'min',-12);
set(handles.slider1,'max',12);
set(handles.slider1,'SliderStep',[1/24,1/24]);
Or more succinctly:
set(handles.slider1,'Min',-12,'Max',12,'SliderStep',[1/24,1/24]);
(By the way, I don't think it makes much sense to set those properties in the slider callback. Typically you'd set them in GUIDE or in the OpeningFcn, or, if they depend on other stuff, set them in the callback of the stuff that they depend on or a related function.)
For the other question, how to display the slider's value in a static text, first create the static text (e.g., in GUIDE), say it's called handles.text, and then in your slider callback, set the text's String from the slider's Value:
function slider1_Callback(hObject, eventdata, handles)
set(handles.text,'String',num2str(get(handles.slider1,'Value')));
end
  2 Comments
Voss
Voss on 31 Dec 2023
You're welcome! Any other questions, let me know. Otherwise, please Accept This Answer. Thanks!

Sign in to comment.

More Answers (0)

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!