MATLAB: Fix Values of a slider in GUI to be multiple of two

guiguideslideslider

Hello! Is it possible to choose the values of a slider? I have a slider that define the number of points used for some FTT transformations. I would like to fix the values of the slider only to be multiples of two, so that sliding I will always chose a multiple of two.

Best Answer

vittorio - you can try discretizing the slider values as at https://www.mathworks.com/matlabcentral/answers/153278-discretizing-matlab-slider-gui. If you know how many values or steps you want in your slider, you could do in the OpeningFcn
function yourGuiName_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
% add a continuous value change listener
if ~isfield(handles,'hListener')
handles.hListener = ...
addlistener(handles.slider1,'ContinuousValueChange',@respondToContSlideCallback);
end
% set the slider range and step size
numSteps = 13;
set(handles.slider1, 'Min', 1);
set(handles.slider1, 'Max', numSteps);
set(handles.slider1, 'Value', 1);
set(handles.slider1, 'SliderStep', [1/(numSteps-1) , 1/(numSteps-1) ]);
% save the current/last slider value
handles.lastSliderVal = get(handles.slider1,'Value');
% Update handles structure
guidata(hObject, handles);
In the slider callback, you would then multiply your slider value by two
function respondToContSlideCallback(hObject, eventdata)
% first we need the handles structure which we can get from hObject
handles = guidata(hObject);
% get the slider value and convert it to the nearest integer that is less
% than this value
newVal = floor(get(hObject,'Value'));
% set the slider value to this integer which will be in the set {1,2,3,...,12,13}
set(hObject,'Value',newVal);
% now only do something in response to the slider movement if the
% new value is different from the last slider value
if newVal ~= handles.lastSliderVal
% it is different, so we have moved up or down from the previous integer
% save the new value
handles.lastSliderVal = newVal;
guidata(hObject,handles);
% calculate the new number of points
numPoints = 2 * get(hObject, 'Value');
end
Related Question