在外部for中使用parfor的两循环错误 [英] Two-loops error using parfor in the external for

查看:302
本文介绍了在外部for中使用parfor的两循环错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要并行化代码以节省时间.我在另一个循环内部有一个循环,我想并行化一个外部循环(因为我认为这种方式使代码更快).我的代码如下:

I need to parallelize a code in order to save time. I have a loop internal to another loop, and I would like to parallelize the external one (because I think it this way the code is faster). My code looks like this:

A = rand(1000,1);
B = rand(1000,1);
Biggers = zeros(1000,1000);
parfor i = 1:size(A,1)
    for j= 1:1:size(B,1)
        if B(i,1) > A(j,1) 
           Biggers(i,j) = A(j,1);
        end
     end
end

但是,如果我以这种方式运行,则会收到错误消息:

but if I run it this way I get the error:

Error: The variable Biggers in a parfor cannot be classified.   
See Parallel for Loops in MATLAB, "Overview".

如果我改为并行处理内部循环(即,将代码设计为:

this condition does not occur if I instead parallelize the internal loop, i.e. if design the code as:

A = rand(1000,1);
B = rand(1000,1);
Biggers = zeros(1000,1000);
for i = 1:size(A,1)
    parfor j= 1:1:size(B,1)
        if B(i,1) > A(j,1)
            Biggers(i,j) = A(j,1);
        end
    end
end

我不明白为什么在第一种情况下Biggers不被视为切片变量,因为每个工作人员都应只关注变量的一行.

I don't understand why in the first case Biggers is not considered a sliced variable, since every worker should focus only on a line of my variable.

我该如何解决问题?

推荐答案

我不确定为什么它不能与外部循环一起使用. MATLAB对于parfor循环中哪些可以进入和哪些不能进入的方面有非常严格的规定,这些规定并不总是很明确.

As to exactly why it does not work with the outer loop I am not sure. MATLAB has very strict regulations on what can and what can't go into the parfor loop which are not always crystal clear.

简单"的解决方案是将您在parfor循环内的所有 包裹到一个函数中,然后parfor突然吃掉所有东西.即

The "simple" solution would be to wrap everything you have inside your parfor loop into a function, then parfor suddenly eats everything. i.e.

function Biggers = parforfunc(A,B,ii)
for jj= 1:size(B,1)
    if B(ii,1) > A(jj,1) 
       Biggers(ii,jj) = A(jj,1);
    end
end
end

将其另存为parforfunc.m并使用

A = rand(1000,1);
B = rand(1000,1);
Biggers = zeros(size(B,1),size(A,1));
parfor ii = 1:size(A,1)
    Biggers = parforfunc(A,B,ii);
end

这篇关于在外部for中使用parfor的两循环错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆