%% Combine afterEach and afterAll
% You can combine afterEach and afterAll to automatically invoke more functions on the results of futures. Both afterEach and afterAll generate future variables that can be used again in afterEach and afterAll.
% Use parfeval to compute random vectors in the workers. With default preferences, parfeval creates a parpool automatically if there is not one already created.

for idx= 1:10
    f(idx) = parfeval(@rand, 1, 1000, 1);
end

% Compute the largest element in each of those vectors when they become ready. afterEach executes the function handle on the output of each future when they become ready and creates another future to hold the results.

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

% To compute the minimum value among them, call afterAll on this new future. afterAll executes a function on the combined output arguments of all the futures after they all complete. In this case, afterAll executes the function min on the outputs of maxFuture after completing and creates another future to hold the result.

minFuture = afterAll(maxFuture, @(r) min(r), 1);

% You can fetch the result using fetchOutputs. fetchOutput waits until the future completes to gather the results.

fetchOutputs(minFuture)

% You can check the result of afterEach by calling fetchOutputs on its future variable.

fetchOutputs(maxFuture)

% Copyright 2012 The MathWorks, Inc.