Update a User Interface Asynchronously Using afterEach and afterAll

You can perform asynchronous computations on workers using parfeval and leave the user interface responsive. Use afterEach to update the user interface when intermediate computations are ready. Use afterAll to update the user interface when all the computations are ready.

Create a simple user interface using a waitbar.

h = waitbar(0, 'Waiting...');

Use parfeval to carry out time-consuming computations in the workers, for example, eigenvalues of random matrices. The computations happen asynchronously and the user interface updates during computation. With default preferences, parfeval creates a parpool automatically if there is not one already created.

for idx = 1:100
    f(idx) = parfeval(@(n) real(eig(randn(n))), 1, 5e2); 
end

Compute the largest value in each of the computations when they become ready using afterEach. Update the proportion of finished futures in the waitbar when each of them completes using afterEach.

maxFuture = afterEach(f, @max, 1);
updateWaitbarFuture = afterEach(f, @(~) waitbar(sum(strcmp('finished', {f.State}))/numel(f), h), 1);

Close the waitbar when all the computations are done. Use afterAll on updateWaitbarFuture to continue automatically with a close operation. afterAll obtains the figure handle from updateWaitbarFuture and executes its function on it.

closeWaitbarFuture = afterAll(updateWaitbarFuture, @(h) delete(h), 0);

Show a histogram after all the maximum values are computed. Use afterAll on maxFuture to continue the operation automatically. afterAll obtains the maximum values from maxFuture and calls histogram on them.

showsHistogramFuture = afterAll(maxFuture, @histogram, 0);

See Also