How to add folders containing class definitions to matlab parpool object

784 Views Asked by At

I would like to use Matlab's parfor to expedite some parts of my code. Some functions needed for the execution reside in a directory that contains a class definition. Hence I add the requisite directory along with required files to the pool object as follows:

% instantiate parallel pool object
poolobj = gcp; 
% add file containing class definition
poolobj.addAttachedFiles(fullfile(pwd,'@Gaussian','Gaussian.m'));
% add specific methods required in parfor loop
poolobj.addAttachedFiles(fullfile(pwd,'@Gaussian','logpredictive.m'));

I confirm by checking that poolobj contains requisite files in the AttachedFiles field. However, when I run parfor, Matlab throws an error:

An UndefinedFunction error was thrown on the workers for 'logpredictive'.
This might be because the file containing 'logpredictive' is not
accessible on the workers.  Use addAttachedFiles(pool, files) to specify
the required files to be attached.  See the documentation for
'parallel.Pool/addAttachedFiles' for more details.

Edit:

Based on answer below, I tried adding the entire directory, but did not work:

poolobj.addAttachedFiles(fullfile(pwd,'@Gaussian'));
1

There are 1 best solutions below

3
Edric On

The function addAttachedFiles can accept folder names as well as file names, so you need to do simply:

poolobj.addAttachedFiles(fullfile(pwd, '@Gaussian'));