Eng
Eng

Reputation: 3

How to stop execution in a Graphic Interface in MatLab

Sometimes my program runs for too long, so I'd like to know if it's possible for the user to stop the program from the graphic interface, whenever he wants.

I've tried, but while the program is running one function it doesn't read another one (for example, one function that the user would say it to stop).

Upvotes: 0

Views: 118

Answers (2)

sebastian
sebastian

Reputation: 9696

If you really want something like a stop button, the only choice is to implement a check in your long-running process that frequently asks whether it should stop or not.

A tiny counter example:

function teststop
    f = figure('pos', [0,0,200,100],...
        'menubar', 'none',...
        'toolbar', 'none');
    movegui(f, 'center');

    c = uiflowcontainer(f, 'FlowDirection', 'topdown');
    uicontrol(c, 'style', 'pushbutton', 'string', 'start', 'callback', @start);
    uicontrol(c, 'style', 'pushbutton', 'string', 'stop', 'callback', @stop);
end

function start(hObject,~)
    fig = ancestor(hObject, 'figure');
    setappdata(fig, 'stop', false);

    % disable another start
    set(hObject, 'Enable', 'inactive');    

    count = 0;
    % increment counter as long as we're not told to stop
    while ~getappdata(fig, 'stop')
        count = count+1; 
        % a tiny pause is needed to allow interrupt of the callback
        pause(0.001); 
    end
    fprintf('Counted to: %i\n',count);

    % re-active button
    set(hObject, 'Enable', 'on');
end

function stop(hObject, ~)
    disp('Interrupting for stop');
    % set the stop flag:
    setappdata(ancestor(hObject, 'figure'), 'stop', true);    
end

Just save it to teststop.m and run. Note that the pause(0.001) is required in any case in order to allow the callback to be interrupted. The above won't work without the pause call.

The check-for-stop of course takes time, so I'd suggest to make the check not too frequent.

Alternatively, if you process is something periodic, like waiting for input or something else to happen, you may be able to implement it with a timer, that can be stopped easily.

Upvotes: 1

GameOfThrows
GameOfThrows

Reputation: 4510

The stop run command in Matlab is ctrl+c or ctrl+break, but if your program causes Matlab to crash, it might not take these commands and you will have to force shut the program. while running the program, try ctrl+c in the command window, it should stop the execution.

Hmmm... is the graphic interface taking too long? You can try adding breaks in between the code to determine what is slowing down the process. Add tic at the beginning and toc at where you want to time the process.

Upvotes: 0

Related Questions