Using a slider in MATLAB GUI

451 views Asked by At

Following the hints given by Benoit_11 in Use a slider in MATLAB GUI, I started adapting his code so to fit my case.

I noticed that when the vector SliderValue*(1:0.1:20).^2 is modified to SliderValue*(1:dt:20).^2, with dt = 0.1, the plot does not show anything. This is required as I want to use an expression defined by variables.

A second question: how can I manually define the axes ranges?

My code:

%function GUI_slider

    % GUI Controls
    
    dt = 0.1;
    t = 0:0.1:100;
    
    handles.figure = figure('Position', [100 100 1000 500], 'Units', 'Pixels');
    handles.axes1 = axes('Units', 'Pixels', 'Position', [60, 120, 900, 300]);
    handles.Slider1 = uicontrol('Style', 'slider', 'Position', [60 40 400 25], ...
                                'Min', min(t), 'Max', max(t), 'SliderStep', [.01 .01], ...
                                'Callback', @SliderCallback);
    handles.Edit1 = uicontrol('Style', 'Edit', 'Position', [150 453 100 20], ...
                              'String', 'Click on slider');
    handles.Text1 = uicontrol('Style', 'Text', 'Position', [70 450 70 20], ...
                              'String', 'Slider Value:');
    handles.xrange = 1:dt:20;           %// Use to generate dummy data to plot
    guidata(handles.figure, handles);   %// Update the handles structure

    function SliderCallback(~,~)        %// This is the slider callback, executed when you release  it or press the arrows at each extremity. 

        handles = guidata(gcf);

        SliderValue = get(handles.Slider1, 'Value');
        set(handles.Edit1, 'String', num2str(SliderValue));

        plot(handles.xrange, SliderValue*(1:0.1:20).^2, 'Parent', handles.axes1);

    end
%end

What should I correct to have it running?

2

There are 2 answers

0
Mansour Torabi On BEST ANSWER

As Cris Luengo noted, if un-comment first line ( %function GUI_slider ) and last line ( %end), dt would be considered as a global variable for all sub-functions inside your main function ( GUI_slider), Therefore, dt is accessible inside the sub-function SliderCallback(~,~) and you can run the code with SliderValue*(1:dt:20).^2.

For the second question, using the function axis you can manually set axes range:

axis([x_min, x_man, y_min, y_max]);

or

set(gca, 'xlim', [x_min, x_max]);
set(gca, 'ylim', [y_min, y_max]);
1
Adriaan On

The problem is that you're not passing dt to the inner SliderCallback function, so it doesn't know what dt is (you should actually get an error telling you that). It should work if you add dt to the function definition

function SliderCallback(~,~,dt)