“the variable in a parfor cannot be classified.” error in Matlab [duplicate]

别等时光非礼了梦想. 提交于 2019-12-11 02:17:27

问题


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


来源:https://stackoverflow.com/questions/35301150/the-variable-in-a-parfor-cannot-be-classified-error-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!