MATLAB: How to overcome this error “variable in a parfor cannot be classified”?

classificationerrorparallel computingParallel Computing Toolboxparforvariable

I have a code that a part of it looks like this simple example:
solution=cell(1,2);
solution{1}=zeros(100000,10);
solution{2}=zeros(100000,1);
parfor Xi=1:size(solution{1},1)
Min_cost=10^9;
for Xj=1:10
Iter_mat=[Xj/1 Xj/2 Xj/3 Xj/4 Xj/5 Xj/6 Xj/7 Xj/8 Xj/9 Xj/10];
Total_cost=Xi^2-Xi;
if Total_cost<Min_cost
Min_cost=Total_cost;
solution{1}(Xi,:)=Iter_mat;
solution{2}(Xi)=Min_cost;
end
end
end
but, I get this error messege: (Error: The variable solution in a parfor cannot be classified. See Parallel for Loops in MATLAB, "Overview".)
I have read the Matlab help and tried many to solve the problem, but I failed.
Any help is appreciated.

Best Answer

It appears that you are trying to make the contents of "solution" into sliced variables. According to the documentation on parfor sliced variables, one of the rules they must follow is
Fixed Index Listing — Within the first-level parenthesis or braces, the list of indices is the same for all occurrences of a given variable.
This is violated by having solution{1} and solution{2} both indexed within the loop. A remedy is to use separate variables like the follwing,
solution1=zeros(100000,10);
solution2=zeros(100000,1);
parfor Xi=1:size(solution1,1)
Min_cost=10^9;
for Xj=1:10
Iter_mat=[Xj/1 Xj/2 Xj/3 Xj/4 Xj/5 Xj/6 Xj/7 Xj/8 Xj/9 Xj/10];
Total_cost=Xi^2-Xi;
if Total_cost<Min_cost
Min_cost=Total_cost;
solution1(Xi,:)=Iter_mat;
solution2(Xi)=Min_cost;
end
end
end
As an aside, I hope the above is a great simplification of your actual code. The example you've given does not require for-loops at all and therefore is not something for which parfor would be the optimal approach.