2013-04-21 19 views
1

我现在正在使用Matlab进行学习,希望了解更多关于并行计算的知识。 Parfor似乎是一种非常有用的技术。我不能让它与下面的代码工作:如何使用双索引获取输出变量以使用parfor?

resultsOfRW = ones(100,N); 

parfor i= 1:100 

    RWs{i} = A; %I want to modify A in every iteration 

    j = 1; 
    S = 2; %just something larger than 1 

    while j <= N && S > 1 
     RWs{i} = DoSomethingRandomly(RWs{i}); % Make some (stochastic) change to RWs{i} 
     S = GetSomeResultFrom(RWs{i}); 

     resultOfRW(i,j) = S; %This is invalid 

     j = j+1; 
    end 
end 

现在,我知道,它与索引J--其不适用于切片变量做。但我不明白为什么,因为这是平行运行的完全有效的。

除了为什么,我怎么能实现这个并行运行呢?

回答

2

M-皮棉显示了以下错误:

Fix the indexing. For a description of the indexing restrictions, see “Sliced Variables” in the Parallel Computing Toolbox documentation.

具体有以下要求不能满足:来解决此

Form of Indexing — Within the list of indices for the variable, exactly one index involves the loop variable.

一个方法是使用一个临时数组:

parfor i=1:1000 
    %# ... 

    tmp = ones(1,N); 
    while j <= N && S > 1 
     %# ... 

     tmp(j) = S; 
     j = j+1; 
    end 
    resultsOfRW(i,:) = tmp; 
end 
+0

谢谢!我尝试了类似的东西,但失败了。显然它需要你在parfor中声明'tmp'(而不是之前)。 – Rur 2013-04-21 18:40:24

+0

好的,我现在开始工作了。但是当我运行它并添加一些'disp(\'现在迭代我')',我不会得到并行结果。并且我的处理器使用率仅为25%(在quadcore上)... – Rur 2013-04-21 18:52:12

+0

'tmp'在'parfor'内声明。除此之外,我真的不知道MATLAB如何并行运行它。也许你可以联系MathWorks获得支持请求,或者等待其他人更熟悉并行编程...(我知道@ Edric在MATLAB + PCT工具箱中在SO上活跃) – Amro 2013-04-22 08:32:43