%% Manually Retrieve Data Sent from the Background
% This example shows how to manually retrieve data in your current MATLAB session that you send from the background.
% Create a PollableDataQueue object.

q = parallel.pool.PollableDataQueue;

%
% The helper function magicWithSend defined at the end of this example sends the sum of a magic square to a DataQueue or PollableDataQueue object, then returns that magic square.
% Use parfeval and backgroundPool to run the function magicWithSend in the background.

f = parfeval(backgroundPool,@magicWithSend,1,q,3);

%
% To retrieve the output from the background, use fetchOutputs. MATLAB returns the output once the execution of magicWithSend is complete.

fetchOutputs(f)

%
% Use the poll function to collect data from the queue.

poll(q)

%
%% Define Helper Function
% Define the helper function magicWithSend. The function creates a magic square, then sends the sum of the magic square to a DataQueue or PollableDataQueue object. After the sum is sent, the function returns the magic square.

function X = magicWithSend(q,n)
    X = magic(n);
    s = sum(X,'all');
    send(q,s);
end

% Copyright 2021 The MathWorks, Inc.