File Exchange Pick of the Week

Our best user submissions

STOP!

Sean's pick this week is Display progress, pause or stop a time-consuming loop by Rafael Oliveira.

Background

It is not uncommon to see questions such asking "How do I stop a for or while loop when a user pushes a button?" in MATLAB Answers. There are a few ways to do this, but usually the results involve checking the state of a toggle button or some flag that has been set by a user. Alternatively, one could consider replacing the for or while loop with a timer which is what I typically recommend.

Rafael's stop makes stopping a loop easy and elegant to do.

for ii = 1:100
    if ~stop.requested
        disp(['Still Running, iteration: ' num2str(ii)])

        % Computationally expensive operation.
        fft2(rand(5000));
    else
        % I clicked said stop
        disp('Stopped')
        break
    end
    drawnow
end
Still Running, iteration: 1
Still Running, iteration: 2
Still Running, iteration: 3
Still Running, iteration: 4
Still Running, iteration: 5
Still Running, iteration: 6
Still Running, iteration: 7
Stopped

This utility also allows you to pause and resume elegantly.

How I found it?

I typically find File Exchange submissions either by randomly browsing, needing some piece of functionality, or trying to help someone not reinvent the wheel. However, I came by this one a little differently. Out of curiosity, I wanted to know which File Exchange submissions contain the string "xkcd". This one came up with a nice little easter egg related to a specific comic.

Turning that mode on:

for ii = 0:0.3:1
    stop.setStatus('xkcd',ii)
    drawnow
    snapnow
end

Comments

What approaches do you usually take to allow for user interactions with a loop or timer?

Give it a try and let us know what you think here or leave a comment for Rafael.




Published with MATLAB® R2014b

|
  • print

コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。