如何在 MATLAB 中的 PARFOR 循环外使用变量?

x.y*_*... 4 parallel-processing matlab parfor

在 MATLAB 中,我有一个变量probaparfor loop如下所示:

parfor f = 1:N
    proba      = (1/M)*ones(1, M);
    % rest of the code
end
pi_proba = proba;
Run Code Online (Sandbox Code Playgroud)

MATLAB 说:“临时变量 'proba' 在 PARFOR 循环之后使用,但它的值是不确定的”

我不明白如何纠正这个错误。我需要使用并行循环,我需要proba在循环之后。这该怎么做?

Dan*_*iel 6

使用时parfor的类是根据这些类别进行分类的。确保每个变量都匹配这些类别之一。对于proba广播变量的非写入访问将是最佳选择:

proba      = (1/M)*ones(1, M);
parfor f = 1:N
    % rest of the code
end
pi_proba = proba;
Run Code Online (Sandbox Code Playgroud)

在循环内写访问的情况下,切片变量是必要的:

proba=cell(1,N)
parfor f = 1:N
    %now use proba{f} inside the loop
    proba{f}=(1/M)*ones(1, M);
    % rest of the code
end
%get proba from whatever iteration you want
pi_proba = proba{N};
Run Code Online (Sandbox Code Playgroud)