MATLAB GUI Tutorial - Slider
28 Oct 2007 Quan Quach 85 comments 17,423 views
Introduction
In this Matlab GUI tutorial, you will learn how to create and use the slider component. Sliders are useful controls for choosing a value in a range of values. Common uses are volume controls, seekers for movie and sound files as well as color pickers. An example of a slider is shown below.

This tutorial is written for those with little or no experience creating a Matlab GUI (Graphical User Interface). If you’re new to creating GUIs in Matlab, you should visit this tutorial first. Basic knowledge of Matlab is not required, but recommended. Matlab version 2007a is used in writing this tutorial. Both earlier versions and new versions should be compatible as well (as long as it isn’t too outdated). Let’s get started!
Create the Visual Aspect of the GUI
-
Start up Matlab, and type
guidein the command line.
-
Choose to create a new GUI using the “Blank GUI(Default)” option.

-
Click on
and add an Edit Text component to the GUI figure. Next, click on
and add a Slider component onto the GUI figure. -
Double click the Edit Text component to bring up the Property Inspector. Change the String property to
0, and change the Tag property tosliderValue_editTextas shown in the figure below:
-
Next, let’s modify the properties of the Slider component. First lets sit the Min property to
0, and the Max property to100. Next, change the Tag property toslider1.
-
Here’s what your figure should look like after you add the components and modify them.

-
At this point, you also might want to add some Static Text components to specify the min and max values of the slider. You can modify their text by double clicking on the component and changing the String property. It’s not required, but I highly recommend it.

-
Save your GUI wherever you please with your desired filename.
Writing the Code for the GUI
Matlab automatically generates an .m file to go along with the figure that you just put together. The .m file is where we attach the appropriate code to the callback of each component. For the purposes of this tutorial, we are primarily concerned only with the callback functions. You don’t have to worry about any of the other function types.
-
Open up the .m file that was automatically generated when you saved your GUI. In the Matlab editor, click on the
icon, which will bring up a list of the functions within the .m file. Select slider1_Callback. 
Add the following code to the function:
%obtains the slider value from the slider component sliderValue = get(handles.slider1,'Value'); %puts the slider value into the edit text component set(handles.slider_editText,'String', num2str(sliderValue)); % Update handles structure guidata(hObject, handles);
-
Now, let’s add the following code to the slider_editText_Callback function:
%get the string for the editText component sliderValue = get(handles.slider_editText,'String'); %convert from string to number if possible, otherwise returns empty sliderValue = str2num(sliderValue); %if user inputs something is not a number, or if the input is less than 0 %or greater than 100, then the slider value defaults to 0 if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 100) set(handles.slider1,'Value',0); set(handles.slider_editText,'String','0'); else set(handles.slider1,'Value',sliderValue); end
-
Save your m-file!
Run and Test the GUI
Now that we’ve completed both the visual and code aspects of the GUI, its time to run the GUI to make sure it works.
-
From the m-file editor, you can click on the
icon to save and run the GUI. Alternatively, from the GUIDE editor, you can click on the
to launch the GUI. The following GUI should appear once you click the icon: 
-
Now, try to put in different types of inputs to test the GUI. Any input that is not a number, less than zero, or greater than 100 should default the slider to a value of zero.
-
And that’s it. Those are the basics of using a Slider component. You can explore the other options that the slider has to offer through the Property Inspector. For instance, you can use the SliderStep property to customize how far you want the slider to move when you press the left and right arrow, or when you click on the scroll bar.
This is the end of the tutorial.
Source files can be downloaded here.
85 Responses to “MATLAB GUI Tutorial - Slider”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


This was very helpfull, thnx 4 helping me out!
Thanks!!!! Am doing coursework - very helpful…
Very nice mate, clearly presented and easy to follow, 10/10
Thanks for the great tutorials I have been living on your tutorials for the past few days and they are helping me drive through… Great work and effort ….
I have some inquiries about the slider,
I would like to have a min value that is not zero on the slider such that the extreme left is a 1 for example. In addition I would like to know how I could set the initial value/ Position of the slider.
Thanks for your help
Hey Eman, thanks for the support… here are the answers to your inquiries
1. You can change min value of the slider by going to GUI builder and double click on the slider to have the properties menu show up. Scroll to Min, and change the value form 0 to 1.
2. To set initial value, here is one way to do it. Paste the following code in the Slider_OpeningFcn. It basically sets your slider value and the text box to an initialized value that you determine.
initval = 10;
set(handles.slider1,’Value’,initval);
set(handles.slider_editText,’String’, num2str(initval));
Thanks a lot for your help Its working Fine now
thanks! these tutorials are helpful
i would like to use the matlab GUI for drawing a graph of ECG signal (only 50 among 500 elements of the data should be displayed first) and to use a slider so that when user click the slider other parts of graph should be displayed just in the same way we use the normal slider. As user press up part of the slider a page moves up and vise versa. i hope you will help
How multiline static text can scroll using slider in GUI. Actually i have a big output to show on static text, not fessible to display on assigned place of Satic text. Scrolling required horizotally and vertically. I required tutorial as i am new in Matlab. Thanks in advance.
Nice work there! Is there any way of displaying the current value of the slider, on it, or aside of it?
Yiannis ==> You can add another “edit text” with a very little fontsize.
Then, you put it just under your slider and you repeat the tutorial steps to “connect” the slider and the new “edit text”.
sorry for my english
Nice Article
extremely good and simple to understand tutorials..not just this one…all of them…
thank you!!
Have you found a way to make the slider update constantly? I realize this would create loads of callbacks, but I find it necessary in some instances. I’ve found no documentation to support this feature.
Realy good work you done here. Helps a lot.
I’ve got a problem and I wonder if you got an idea how to solve it.
I’m using a slider that should cover the area from 0-63and I’m only interested in integers. I’ve connected it to an edit as you described.
I’ve found out that I should use 1/64 as sliderstep but the property inspector oly takes the decimals and thats give me 1/64~0.016 wich isn’t good enough.
Dose anybody know how to solve this?
Thanks…
Sorry about my unreadable writing.
I’ve found out that I should use 1/64 as sliderstep but the property inspector only takes three decimals and that gives me 1/64~0.016 wich isn’t good enough.
Yes, you have to use decimal from 0 to 1 which is ‘1 / (max - min)’. What you can do is use wincalc to determine what the step is and copy and paste the answer into the property editor for the slider x and y values (x is for the direction buttons of the slider and y is for the trough). When you click on it, it will show the full value (0.015625) until you click away then it will probable show what you are experiencing. This is not a problem, it should still work fine.
In the callback for the slider, you may want to ensure that you are getting integers by using something like the following:
If you have an edit box called textInput and a slider called textInputSlider,
for the slider
set(handles.textInputSlider, ‘String’, floor(get(hObject,’Value’)));
Thanks
Hello,
Your website helped me alot. I do not know how to say thank you. I have read quite a lot of text books on GUI. But the final implimentation of the GUI has not been properly explained except you. Looking forward to read more educative items from your website.
so i declared a global variable called “wavelength1″ in both edit text and slider callbacks. then i set “wavelength1 = sliderValue” so that the two are linked. my problem is that when i go to enter a value in the edittext and then hit enter it does a carriage return rather than changing the position of the slider. i found that if i enter a value in the edittext and then click somewhere else, the slider changes position. but how can i make it so that when i press enter in the edit text it will change the position?
Hi Kaspi,
I’m not sure why you would declare a global variable and link them. The way I coded it in this example has the text box and slider already linked. Try downloading the source code and playing around with it.
Quan
[...] You can download the sample input file here. (Right Click the link and use “Save As”) The sample file is the HTML code for the Slider Tutorial. [...]
QUan,
I linked them because i want either the slider and the box to output their values that i can work with them outside of their callbacks. (if i didn’t link them with a global variable, the text/slider combo would be pretty useless as i wouldn’t be able to use their values anywhere else). anyways, do you know of a way to update the text instantaneously? e.g. when i’m dragging the slider around, the textbox displays the value of the slider position.
also, do you know how to make it so that if i enter a value in the textbox and hit enter (on the keyboard) it would “be stored”. right now your sourcefile does a carriage return (new line) when i hit enter. thanks bud.
kaspi
Kaspi,
The handles structures that contains all the GUI components can be accessed in any part of your GUI code. This means you can access the slider value within any part of your gui by using:
If you wanted to access these files outside of the GUI framework, then that is a different matter.
I’ll try to answer the rest of your question later when I have access to MATLAB.
Quan
Thank you so much! I looked for hours through the MATLAB help to find a way to change the static text programmatically, and found nothing.
Is there a way to get slider values live, as the user drags the location box back and forth?
Thanks again,
Nathan
Thank you very much for this tutorial. It is very easy to understand and applicate.
I hope the remaining courses are also like this.
The tutorial on how to set up a slider is excellent. I would like to know how to set up multiple sliders so that I could plot a function as each slider (variable) changed.
Thank you,
John
I too am wondering if there is some way to make the textbox update before the mouse button is released. It would be nice to know the value of the slider before releasing the mouse button. Any way to do this???
Hi,
I think there is a typo: in point 4 you write
‘Put sliderValue_editText … as in the figure’, but in the figure there is slider_editText
Regards
ale
Hello there,
I cant see the connection between box and the slider. How do you do that? I did all steps but the text does not seem to be updated with the movement of the slider.
hello,
i use slider to show all images i store it how i can back by slider to go back to previous image.
thanks
Thank you so much. This site is very useful for me.
When I move on the scroll bar, how can I make an integer on display, not floating point?
Hi Villy,
Some useful rounding tools are: round(x), floor(x), ceil(x).
‘Round’ rounds to the nearest integer, ‘floor’ always rounds down to the closest integer, and ‘ceil’ rounds up to the closest.
You could add a line to step one (page 2) to something like this:
Hope this helps.
-Zane
Hi Zane,
Thanks for your assistance.
It’s sloved.
Thanks&Regards,
Villy
Great tutorial. Thank you.
what about the coding??????
Thanking you guys for an excellent tutorial on GUI…. for beginners…
also, the slider tutorial was also very good….
how to do the reverse of what is described here??
i.e., i need to know as we click the mouse and move the slider, how to detect and continuously update the edit text box…?? Please help…
I’m new to matlab, how do you do a GUI with say, 3 sliders in it?
hi i am new to using matlab. i am trying out wat is given in the tutorials. now can u please tell me how do i load a picture on to gui and perform other functions or design the backend of my program in matlab
it’s so helpful! I am searching for this information for a couple of days. this is the most helpful one.
[...] MATLAB GUI Tutorial - Slider MATLAB GUI Tutorial - Pop-up Menu MATLAB GUI Tutorial - Plotting Data to Axes MATLAB GUI Tutorial - Button Types and Button Group MATLAB GUI Tutorial - A Brief Introduction to handles MATLAB GUI Tutorial - Sharing Data among Callbacks and Sub Functions Video Tutorial: GUIDE Basics More GUI Tutorial Videos From Doug Hull [...]
Hello,
Thanks for posting the tutorial, great work.
I get two error messages when trying to run the slider at the end of the tutorial
Error in ==> gui_mainfcn at 75
feval(varargin{:});
Error in ==> slidertest at 44
gui_mainfcn(gui_State, varargin{:});
Could you please tell me what these might mean
Thanks
Fergal
@Fergal, You may be running an older version of MATLAB. If you go through the steps in the tutorial, you can recreate the GUI pretty quickly
@Quan Quach,
Thanks for your response, I am running version 7 r14, I have debugged some of the m code and i can get the slider to control the numbers in the text box but not able to get the input in the text box to control the slider.
1. In Matlab 2006b, Any simulink block is there that allows you to vary a states of the input (except slider gain) during a simulation?
2. How to control the simulink model using GUI?
hi.. is their a way to get a scroll to move along a graph.. i have a set of data that i am plotting.. but i dont have enough room to show clearly..
How do you vertically align the text in a text box?
REALLY,FANTASTIC
I AM AN ELECTRICAL ENGINEERING STUDENT AT MEKELLE UNIVERSITY.
U HAVE CHANGED MY WAYS. 10Q
I WILL BE WITH U AND HOPE CONTRIBUTE MUCH TO YOUR EFFORTS.
Hi all,
I created the matlab GUI to control the simulink model. when these two *.mdl and *.fig running in the same workspace. Then, its working perfectly.
After that, i converted these two files into two different *.exe (mdl.exe and gui.exe) files. now i runned these .exe files but, its not working. I know both the workspaces are different some intermediate file should come to interface these two .exe files.
How to do?
Please help me..
This is a great and useful website. Thanks for putting it up and maintaining it. I have the same problem as Feral- moving the controls the numbers in the text box but not vice versa. Any ideas?
@ Jibido,
If you’ve completed this whole tutorial, the ability to make the numbers control the slider bar is a good exercise to try on your own. I’ll list the steps that you’ll need to do:
1) ‘Get’ the value from the editText box.
2) Convert that value from a string to a double.
3) ‘Set’ the sliderValue to the double you got above.
4) Update your handles structure
(all of these steps are done with some variation in the tutorial)
One thing to note: the slider box won’t update as you type in the numbers, but will after you hit ‘enter’ or click outside the text box.
Send us code questions/issues if they come up!
-Zane
Hey, thanks a lot
but can we set the max sliderValue as a length of other variable?:
maxsliderValue =length(X);
or something like that?
Dear All,
Slider tutorial is working nicely with me but one thing i could not figure out is which is:
2. Now, try to put different types and so on …
i gave to slider -10 to 100 but still showing 0 to 100. I was expecting to get 0 when it is set to values < 0.
Any idea how to make it working?
Cheers,
Nasser.
Hi?
I made one interface in Matlab. that is running now. But I wanna to rearrange that GUI. So that I want to know “How to apply TAB strip in Marlab? ”
Is there anyone help me?
hi
thx ….good tutorial.
plz tell me How to make html file of GUI?
in html page, button should work.
reply soon
thx
thanks Thanks for your i want mor and mor in gui
Thanks alot very informative. I have a question. How can you make the slider give only whole numbers. Because sometimes when i slider the bar i get decimal number like 45.345 or 59.222. How can you tell it to give only whole number or integer. Thx
Mark,
Please check out comments #31 and #32. Let us know if you get other questions!
-Zane
Hey,
Thx for the nice tutorial on slider, actually im stuck with something. I am plotting a large plot where i have thousands of values on the vertical axis and like 20 values on the horizontal axis. I wish to plot it in a figure and only getting certain 20-30 values on the output at a time…. basically i just wanna scroll through it like we do on webpages. I am not a Matlab genious so i need kinda help with this.
regards
Excellent tutorial! This was very helpful in developing my statistics package for a suite of robot sensors. Keep up the good work!
Thanks for this. Very helpful. One thing that is very worth while pointing out is that you have to run the file from the within .m file. If you try running it from the .fig file it falls over in the big heap.
how i cane change the step of slider
Am i the only one who gets errors? *crye*
Any clue???
———-Error shown—————————————————————————
??? Reference to non-existent field ’slider_editText’.
Error in ==> slider_box>slider1_Callback at 88
set(handles.slider_editText,’String’, num2str(sliderValue));
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> slider_box at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==> @(hObject,eventdata)slider_box(’slider1_Callback’,hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
————————————————————————————
Ok i fixed it
The tags are wrong
Hi,
This is a very helpful thread. I have a problem with my GUI.
In my GUI, I am trying to display multiple slices of MR images. The slider is supposed to help in scrolling through the multiple slices of the same volume. I am using an activeX control for the slider. I am able to scroll through the image slices but there are 2 problems:
1. the first slice is getting displayed on d same Gui but when i press the up motion button, then next slice gets displayed in another figure window.
2. because of the occurance of this new figure window the slider value is not getting updated in the text box.
Kindl help in.
Regards,
shruti
Shruti,
It’s a little hard to see what’s going on without a snippet of code, and I haven’t used ActiveX controls before, but it sounds like you just need to keep referencing the handles of the figure/axes that you want to plot to. You can use the ‘axes’ tool in the GUIDE editor and then whenever plotting your new MR image, calling axes(handles.tag) or figure(handles.tag) before your plotting command should work. This is all presuming ActiveX isn’t interfering with this somehow.
Hopefully this helps somehow?
-Zane
excuse
como se hace para aumentar el slider de 1 en 1, example
0, 1, 2 ………. 100
Anonymous,
Si entiende ingles, el comentario #32 describe esto (yo creo). Lo te tratare explicar. En la seccion “Writing the Code for the GUI” cambie su funccion a:
Ojala que entienda.
Buena suerte.
Wonderful tutorial!
Quan, I have two variables in a quadratic equation, x & y (quatratic in x) and x has range of values. I am able to produce a plot for the equation now (thanks to your tutorial again) and believe that we can set slider for x. But could not club both (plotting and slider) in the same GUI (I am a novice matlab user). Can you help me here?
The equation is: P = n*x^2+x+n*x*y+c ; (n and c are constants)
where x = -2:0.01:2
What actually I want to display is changing characteristics of the curve ‘P’ with change in value of x.
Tons thanks in advance
Jeet,
This is very doable. You need to do 2 main things: Change the limits on your slider, and then plot your function.
Changing limits:
This can be done in the inspector if you have your slider as the active panel (just click on the slider tool, double click to get inspector to pop up). Find min/max values and set those to -2/2.
This can also be done with commands:
Now your sliderValue is your ‘x’ that you change.
Plotting the function:
I made a separate axes tool in the GUI editor to plot this. In the slider1_Callback and the editText1_Callback functions, you need to get the slidervalue and the plotting function, and create some y independent variable vector as seen below
You’ll have to update the editText ranges of 0–>100 to -2–>2 as well. This is a linear function since you are taking discrete steps in ‘x’ and plotting over ‘y’. The same can be done for parabolas, but make sure you use …y.^2+c instead of just …y^2+c
happy hacking,
Zane
Genious!
Thank you Zane!
Hi, everyone:
I have a question need help. I want to set up a static text to display slider’s min value.
However, when I type:
set(handles.text1, ‘String’, get(handles.slider1, ‘Min’);
An error message appear:
??? Attempt to reference field of non-structure array.
Could anyone help me to solve this problem? Thank you.
You’re close stLeth,
The min value is in double format, you want it to be string format to put it into ‘String’. Also you’re missing a parenthetical.
Try this:
Thank you, Zane:
I correct my code to: set(handles.text1, ‘String’, get(handles.slider1, ‘Min));
Same error message appears again: ??? Attempt to reference field of non-structure array.
I put the set() code inside text1_CreateFcn(hObject, eventdata, handles) function. Is this a mistake? Many thanks.
Hi, Zane:
I tried your code, but same error message appeared. Thank you.
Yup, you’re in the wrong function. You haven’t established either your slider or static text fully when you call text1_CreateFcn…
You need to put that block of code I gave you in Callback functions for whatever buttons you want (slider, edit_text, etc)
Hi, Zane:
I move the code to slider1_Callback function. It works. Thank you.
Hi, Zane:
How could I avoid hard coding the static text’s value each time the slider’s value changed? (For example, if I want to use static text to display slider’s minimum value, I change the slider’s ‘Min’ value and the static text will change as well.)
Thank you for your help.
thanks for this tutorial. its really helps in GUI programming.
Thank you bro…it really helped
hey all,
i hav trid ths exampl and gt it corrctly!!!!!!
now i trid 2 put two sliders with two txt boxs. for th 1st slider th range is 1-10, for th second th range is 130-170.
plz help me with ths!!!!!!!
hey all,
how to give interval of 1? i mean the x and y values in silderstep property…i found it pretty confusing :/
help me out
hi
i want to ask that how can i implement a function on slider that when i move the slider on a particular value the input image gets transformed and shows the reult in output image
thnx for the help
hey all,,
i’m facing a problem when connecting GUI windows. i can connect the windows but the sliders does not work. the sliders are working only in separate windows.
pls help me with this.
thank you
[...] MATLAB GUI Tutorial - Slider MATLAB GUI Tutorial - Pop-up Menu MATLAB GUI Tutorial - Plotting Data to Axes MATLAB GUI Tutorial - Button Types and Button Group MATLAB GUI Tutorial - A Brief Introduction to handles MATLAB GUI Tutorial - Sharing Data among Callbacks and Sub Functions Video Tutorial: GUIDE Basics More GUI Tutorial Videos From Doug Hull [...]