Main Content

Update User Interface Asynchronously Using afterEach and afterAll

This example shows how to update a user interface as computations complete. When you offload computations to workers using parfeval, all user interfaces are responsive while workers perform the computations. You can use waitbar to create a simple user interface.

  • Use afterEach to update the user interface after each computation completes.

  • Use afterAll to update the user interface after all the computations complete.

Use waitbar to create a figure handle, h. When you use afterEach or afterAll, the waitbar function updates the figure handle. For more information about handle objects, see Handle Object Behavior.

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

Use parfeval to calculate the real part of the eigenvalues of random matrices. With default preferences, parfeval creates a parallel pool automatically if one has not already been created. For efficiency, preallocate an array of Future objects.

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

You can use afterEach to automatically invoke functions on each of the results of the parfeval computations. Use afterEach to schedule another set of future objects to compute the largest value in each of the output arrays after each future in the f completes.

maxFuture = afterEach(f,@max,1);

You can use the State property to obtain the status of futures. Define an anonymous function that updates the fractional wait bar length of h to the fraction of Future objects that have finished executing. The updateWaitbar anonymous function computes the mean of a logical array in which an element is true if the State property of the corresponding Future object in f is "finished".

updateWaitbar = @(~) waitbar(mean({f.State} == "finished"),h);

Use afterEach and updateWaitbar to update the fractional wait bar length after each future in maxFuture completes. Use afterAll and delete to close the wait bar after all the computations are complete.

updateWaitbarFutures = afterEach(f,updateWaitbar,0);
afterAll(updateWaitbarFutures,@(~) delete(h),0)

Use afterAll and histogram to show a histogram of the results in maxFuture after all the futures complete.

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

See Also