Pausing Matlab Script or Function on certain user event

浪子不回头ぞ 提交于 2020-01-04 02:11:30

问题


I know that there is the possibility of Matlab of pausing a Matlab function or script by using input() thus when I have a for-loop and want to pause it every iteration:

for i = 1:N
  reply = input(sprintf('Pausing in iteration %d! Continue with Enter!', i), 's');

  % Calculations
end

but how to get the following working: Usually it runs without pausing (as if the input() wouldn't be there) but when the user does something (perhaps press a key, a button, or something similar in matlab), the script/function does PAUSE each iteration until the the user does it again, thus something like this. E.g. let's say there is the possibility of matlab to toggle a variable whenh pressing a certain hotkey combination, e.h. Ctrl+Alt+A toggles the variable myToggle between 0 and 1 I could easily do:

for i = 1:N
  if(myToggle == 1)
    reply = input(sprintf('Pausing in iteration %d! Continue with Enter!', i), 's');
  end 

  % Calculations
end

Thanks in advance!

EDIT: Just found ONE possible solution here: Function to ask a MATLAB program to wait for an event before continuing execution I could create a file on the beginning of my function/script and pause on the next iteration when it doesn't exist anymore. But that would require the user to rename the file which isn't quite that 'comfortable'... Any other ideas? :)


回答1:


You can use a simple GUI with a button; once pressed the execution halts on the next iteration.

function testGUI()
    doPause = false;
    figure('menu','none', 'Position',[400 400 150 30])
    hb = uicontrol('Style','pushbutton', 'String','Pause', ...
        'Callback',@buttonCallback, 'Unit','Normalized', 'Position',[0 0 1 1]);
    %drawnow

    while ishandle(hb)
        %# check if the user wants to pause
        if doPause
            pause()             %# pauses until user press any key

            %# reset
            doPause = false;
            if ishandle(hb), set(hb, 'Enable','on'), drawnow, end
        end

        %# Calculations
        disp(rand), pause(.1)

        %# keep the GUI responsive
        drawnow
    end

    %# callback function for the button
    function buttonCallback(hObj,ev)
        doPause = true;
        set(hObj, 'Enable','off')
    end
end



回答2:


If you are simply wanting to pause the script from running until the user presses return consider using the pause command in MATLAB



来源:https://stackoverflow.com/questions/6472731/pausing-matlab-script-or-function-on-certain-user-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!