MATLAB: Trouble with accessing variable in parfor loop

addattachedfilesparforparpool

Hello all,
I am trying to do batch processing and I am having trouble implementing the parfor loop. I have a variable (a movie frame), that I want to subtract from every frame in a movie after I load in the frames. The basics of my loop look like this.
load('gray_mean_frame.mat');
set(handles.testMovieButton, 'String', 'Please Wait');
poolobj = parpool('local',4);
addAttachedFiles(poolobj,{'gray_mean_frame.mat'});
parfor frameNumber = 1:numFrames
movieFrame = read(readerobj, frameNumber);
ghostFrame = gray_mean_frame - movieFrame;
end
I always get the error
"An UndefinedFunction error was thrown on the workers for 'gray_mean_frame'.
This might be because the file containing 'gray_mean_frame' 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."
But I think I am correctly passing the file gray_mean_frame to the workers. gray_mean_frame.mat is a file which contains the variable gray_mean_frame, among a couple others. I've also tried making gray_mean_frame a global variable but it did not help. It is not clear to me what I am doing wrong. Thank you for any help.

Best Answer

The problem here is that unfortunately the PARFOR analysis is based on the text of your program, and in this case the analysis cannot deduce that gray_mean_frame is a variable. You should be able to fix this by making a minor change:
data = load('gray_mean_frame.mat');
gray_mean_frame = data.gray_mean_frame;