2014-12-04 155 views
0

有時我的程序運行時間過長,所以我想知道用戶是否可以在圖形界面上隨時停止程序。如何在MatLab中的圖形界面中停止執行

我試過了,但是當程序運行一個函數時它不會讀取另一個函數(例如,用戶會說它停止的一個函數)。

回答

1

如果你真的想要一個像stop這樣的按鈕,唯一的選擇就是在長時間運行的過程中執行檢查,經常詢問是否應該停止。

一個微小的反例:

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 

它只是保存到teststop.m和運行。 請注意,在任何情況下都需要pause(0.001)以允許回撥中斷。如果沒有暫停呼叫,以上方法無法工作。

當然,check-stop-stop需要時間,所以我建議不要過於頻繁地檢查。或者,如果您處理的是週期性的事情,比如等待輸入或其他事情發生,您可以使用timer來實現它,這可以輕鬆停止。

0

Matlab中的停止運行命令是ctrl + c或ctrl + break,但是如果你的程序導致Matlab崩潰,它可能不需要這些命令,你將不得不強制關閉程序。在運行程序時,在命令窗口中嘗試ctrl + c,它應該停止執行。

嗯......圖形界面花費的時間太長了嗎?您可以嘗試在代碼之間添加中斷以確定什麼會減慢流程。在開始處添加tic,並在您想要定時的地方添加tic。

+0

我認爲這個問題是針對圖形界面的用戶的。他不能按ctrl + c ... – Adiel 2014-12-04 09:27:35