GUI: adjust axes values with 2 different sliders

2 views (last 30 days)
I want to select 2 values chosen by 2 different sliders and set these values as the min and max of an axes. So, slider_a should give the min value of the axes, slider_b the max value of the axes. I failed to do so... here my initial code:
function slider1_Callback(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
slider1_val=get(handles.slider1,'value')
set(handles.text1,'string',slider1_val)
get(handles.axes1,'Xlim')
set(handles.axes1,'Xlim',slider1_val) %%x min value should be slider1 val.; max slider2 val.

Accepted Answer

Geoff Hayes
Geoff Hayes on 22 Sep 2014
Marcel - you almost have the correct code, you just need to pass a vector as the value for the Xlim parameter. Since slider1 corresponds to the minimum value for you axes limit, then just change the above code to
function slider1_Callback(hObject, eventdata, handles)
minVal = get(handles.slider1,'Value');
maxVal = get(handles.slider2,'Value');
set(handles.axes1,'Xlim',[minVal maxVal],'XTick',floor(linspace(minVal,maxVal,5)));
I've added the XTick parameter so that the x-axis ticks are linearly spaced from the minimum to the maximum value along the axis (there are 5 ticks displayed).
And this same code can be re-used for the slider2_Callback. In order to prevent code duplication, you can do something like the following
function slider1_Callback(hObject, eventdata, handles)
adjustAxisLimits(handles);
function slider2_Callback(hObject, eventdata, handles)
adjustAxisLimits(handles);
function adjustAxisLimits(handles)
minVal = get(handles.slider1,'Value');
maxVal = get(handles.slider2,'Value');
set(handles.axes1,'Xlim',[minVal maxVal],'XTick',floor(linspace(minVal,maxVal,5)));
So both slider callbacks call the same function to adjust the limits.

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!