function matlab_example
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% MATLAB serial and parallel            Fri Mar 20. 2015, 16:03:35 CET
%%        job example @ LRZ            Nicolay J. Hammer, hammer@lrz.de
%%                                           Leibniz-Rechenzentrum, LRZ
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Define the number of parallel workers. In this example this
% number is read from the environment variable MATLAB_POOL_SIZE,
% similar to the OMP-NUM-THREAD variable when using OpenMP.
global Nworker
Nworker = getenv('MATLAB_POOL_SIZE');
Nworker = str2num(['uint8(',Nworker,')'])

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% serial part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
a=4+4;
b=2^a;
save('matlab_example.out','a','b','-ascii','-double');
save


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% parallel part, if MATLAB_POOL_SIZE 
%% environment variable is defined
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%--------------------
% open parallel pool
if isempty(gcp('nocreate'))
tic;
    poolobj = parpool('local',Nworker)
toc
end


%-------------------
% data size
p = gcp('nocreate');
Nlarge=75*p.NumWorkers

%-------------------
% distributed data
tic;
fprintf('\nDistributed Data: ');
DistArr = distributed.rand(Nlarge);
gather(DistArr*DistArr);
toc


%-------------------
% data size
Nlarge=250*p.NumWorkers

%---------------------------------------
% single program multiple data (SPMD):
fprintf('\nSingle Program Multiple Data (SPMD): ');
tic;
spmd
    a=sum(sum(rand(Nlarge)));
    b=sum(sum(rand(Nlarge)));
    c=sum(sum(rand(Nlarge)));
end
toc


%-------------------
% data size
Nlarge=500*p.NumWorkers

%--------------------
% parallel for loop     
fprintf('\nParallel for Loop: ');
tic;
parfor i=1:p.NumWorkers
    a=sum(sum(rand(Nlarge)));
end
toc

%----------------------
% close parallel pool
if ~isempty(gcp('nocreate'))
tic;
    fprintf('\n');
    poolobj = gcp('nocreate');
    delete(poolobj);
toc
end
exit;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% END
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
