Search code examples
matlabuser-interfaceslidermatlab-figurematlab-gui

Slider disappears from GUI after being used


I try to make a MATLAB GUI programmatically and face the problem that my slider disappears after using it. I isolated the problem to keep the code short. In this GUI I want to refresh the plotmatrix each time the slider is used (ignore the fact that the value of the slider is completely irrelevant to my program, as mentioned before I really wanted to keep the code clean that's why I also removed this functionality). Here's the code (you have to run it as function):

function StackOverflowQuestion_GUI()
    % clear memory
    close all; clc;

    % initialize figure
    f = figure;

    % create main axes
    AX_main = axes('Parent',f,...
        'Units','normalized','Position',[.1 .2 .8 .7]);

    % create slider
    uicontrol('Parent',f,...
        'Style','slider','Callback',{@sliderCallback,AX_main},...
        'Units','normalized','Position',[0.05 0.05 0.9 0.05]);

    plotmatrix(AX_main,randn(500,3));
    title('Random Plotmatrix');
end

function sliderCallback(~,~,AX_main)   % callback for slider
    plotmatrix(AX_main,randn(500,3));
    title('Random Plotmatrix NEW');
end

Any help is appreciated! I think I misunderstood the concept of AXES. When I plot to the AXES-handle I created, why are other parts of the figure affected as well? If someone could explain to me how this graphic-handle system basically works that would be very nice too!


Solution

  • When you call plotmatrix, the function completely redraws the figure, to conserve other elements you should use hold on; hold off; statements:

    function StackOverflowQuestion_GUI()
        % clear memory
        clear; close all; clc;
    
        % initialize figure
        f = figure;
    
        % create main axes
        AX_main = axes('Parent',f,...
            'Units','normalized','Position',[.1 .2 .8 .7]);
    
        % create slider
        uicontrol('Parent',f,...
            'Style','slider','Callback',{@sliderCallback,AX_main},...
            'Units','normalized','Position',[0.05 0.05 0.9 0.05]);
    
        plotmatrix(AX_main,randn(500,3));
        title('Random Plotmatrix');
    end
    
    function sliderCallback(~,~,AX_main)   % callback for slider
        hold on;
        plotmatrix(AX_main,randn(500,3));
        hold off;
        title('Random Plotmatrix NEW');
    end