MATLAB: Parfor loop variable cannot be classified!

classifiedparallel computingParallel Computing Toolboxparfor

When I try to execute the above code with parfor instead of using for, I get the following error :
Error: The variable study in a parfor cannot be classified. See Parallel for Loops in MATLAB, "Overview".
I think the "Form of Indexing : Within the list of indices for the variable, exactly one index involves the loop variable." rule for sliced variables in parfor is causing the issue. (Because study(i).run(j) has not been indexed according to parfor requirements.) But since I have a structure with different fields and I need to update the field 'run' in the structure 'study', is there any way i could make this code compatible with parfor ? Any help/suggestion is really appreciated!

Best Answer

No, a parallelization of this code is not possible. E.g. in this line:
study(i).run(j).result = ...
You write a specific value, which depends on the PARFOR loop counter j. Afterwards you try to save the struct study to a file:
save([study_path study(i).name '.mat'], 'study');
But then this file will be overwritten in each iteration and the contents of the struct depends on the currently processed thread. This is such confusing and the resulting file will contain the struct as created in the last processed thread - which is a kind of random.
At first I'd move the writing of the file outside the PARFOR loop, such that 1. the slow and colliding disk access does not slow down the program dramatically and 2. the final value of the file is well-defined and reproducible.
When the netsed struct is still a problem, try a cell (what is "i"?!):
runC = cell(1, size(study(i).J, 1));
...
Sorry, I give up here. The nested creation of nested structs looks too confusing. But the general idea would to create the different data separately in a cell array and insert them to the struct afterwards.
Related Question