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 these computations. In this example, you 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...');

waitbar.png

Use parfeval to calculate the real part of the eigenvalues of random matrices. With default preferences, parfeval creates a parallel pool automatically if one is not already created.

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 parfeval computations. Use afterEach to compute the largest value in each of the output arrays after each future completes.

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

You can use the State property to obtain the status of futures. Create a logical array where the State property of the futures in f is "finished". Use mean to calculate the fraction of finished futures. Then, create an anonymous function updateWaitbar. The function changes the fractional wait bar length of h to the fraction of finished futures.

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