x.y.z...
x.y.z...

Reputation: 269

How to use a variable outside a PARFOR loop in MATLAB?

In MATLAB, I have a variable proba and I have a parfor loop as showing below:

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

MATLAB said that: "The temporary variable 'proba' is used after the PARFOR loop, but its value is nondeterministic"

I do not understand how to correct this error. I need to use a parallel loop and I need proba after the loop. How to do this?

Upvotes: 4

Views: 3868

Answers (1)

Daniel
Daniel

Reputation: 36710

When using parfor the classes are classified according to these categories. Make sure every variable matches one of these categories. For non-writing access to proba a Broadcast-Variable would be the best choice:

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

In case of writing access within the loop, a sliced variable is nessecary:

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};

Upvotes: 6

Related Questions