-->

“the variable in a parfor cannot be classified.” e

2019-07-17 18:32发布

问题:

This question already has an answer here:

  • parfor in matlab. sliced variable and nested loop 1 answer

I am trying to implement a very simple program with parfor but I get some errors. I saw nearly all of the SO questions for a possible duplication but non of them was similar to my question situation. The error I get is :

Error: The variable log_likelihood_II_with_entropy in a parfor cannot be classified.

My code is written below:

em_iterations=10;

users=5;
log_likelihood_II_with_entropy=zeros(users,em_iterations);

parfor u = 1:1:users
      for current_iter=1:1:em_iterations
           log_likelihood_II_with_entropy(u,current_iter)=rand();               
      end
end

回答1:

Since log_likelihood_II_with_entropy relies on both the parfor index (u) and an "inside index" (current_iter) it cannot be classified. Every parfor iteration is independent from the others and they are not executed in order (that is, u will not necessarily go from 1 to users in order 1,2,3,4,...,users).

My suggestion is to let the single parfor iteration (worker) build an entire row of log_likelihood_II_with_entropy.

parfor u=1:users
    single_row=zeros(1,em_iterations);
    for current_iter=1:1:em_iterations
        single_row(current_iter)=rand();
    end
    log_likelihood_II_with_entropy(u,:)=single_row;
end

In this manner every parfor task (the parfor body itself) will preallocate and evaluate a single row, no matter what the u value is. And then it will replace/concatenate such value in the log_likelihood_II_with_entropy matrix.



回答2:

Parfor loops don't like it when you have 2 variables because it has the potential to get confused. Either use cell arrays to store instead, or else switch the order of your for and parfor loops, as shown below.

em_iterations=10;

users=5;
log_likelihood_II_with_entropy=zeros(users,em_iterations);

for u = 1:1:users
      parfor current_iter=1:1:em_iterations
           log_likelihood_II_with_entropy(u,current_iter)=rand();               
      end
end