Limit x-axis to specific values in GUI

11 views (last 30 days)
Hello, I have a pushbutton which plots any function the user typed in an editable text. I also have two sliders, slider1 and slider2, who should dictate the limits of the x-axis of my plot. So slider1 should give the lower bound and slider2 the upper bound of the x-axis to display. My code doesn't work, I hope someone can help me with this:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
f = get(handles.edit1, 'string')
x = 0:0.1:1;
m = get(handles.slider1, 'Value')
n = get(handles.slider2, 'Value')
set(handles.axes1, 'XLim', [m, n])
axes(handles.axes1)
plot(eval(f))
Thank you!
  7 Comments
Robert Eisenbecker
Robert Eisenbecker on 24 Oct 2017
I'm sorry for being too vague, I will try to explain it better now:
I have an edit box in which the user has to insert a function. After pushing a button, the function in the edit box is plotted into axes1. This works perfectly fine. My next task is to include two sliders m and n which determine the range of the x axis [m n]. So, for example, if I type x in the edit1 box, then it will plot f(x) = x into my axes1. Or if I want to show f(x) = x only between 0.1 and 0.5 on the x axis, I adjust the sliders and then after pushing the button, the plot will be updated accordingly.
Because plotting the functions works, I don't see why I cannot give plot() an equation. It correctly plots everything I put into the editbox, e.g. sin(x), x.^2+x*2, etc. I have defined x to be x = 0:0.1:10. I set the sliders to be between 0 and 1. I know the values of the sliders because they show up in the command window and they seem to be correct.
Robert Eisenbecker
Robert Eisenbecker on 24 Oct 2017
Nevermind, I have found a solution using ezplot, where I can easily edit the xmin and xmax parameters. Thank you for your help still!

Sign in to comment.

Answers (1)

Jan
Jan on 24 Oct 2017
Avoid setting the current axes actively. Better define the parent object to draw in:
% Instead of
axes(handles.axes1)
plot(eval(f))
% use
plot(handles.axes1, eval(f))
Is the 'NextPlot' property of the axes set to 'add'? This is equivalent to hold('on'). Otherwise a plot() command might reset the limits.
If the plot vanishes when the sliders are used, it sounds, like the problem is in the slider's callback, not in the one of the pushbutton.
  1 Comment
Robert Eisenbecker
Robert Eisenbecker on 24 Oct 2017
I have found a way with ezplot, thank you for your answer still!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!