Parfor variable cannot be classified

2 vues (au cours des 30 derniers jours)
Chuck37
Chuck37 le 27 Juin 2019
Modifié(e) : Edric Ellis le 28 Juin 2019
I'm completely stumped by my inability to use parfor for a simple problem. I've boiled it down to a ridiculous case. Can someone please explain?
function b=wtf(a)
sz = size(a);
b=a;
parfor x=1:sz(1)
for y=1:sz(2)
b(x,y) = 5;
end
end
Calling this results in an error:
>> wtf(zeros(3))
Error: File: wtf.m Line: 8 Column: 9
The variable b in a parfor cannot be classified.
See Parallel for Loops in MATLAB, "Overview".
Is it actually not possible to use parfor when the size of the input is not absolutely fixed ahead of time?

Réponse acceptée

Edric Ellis
Edric Ellis le 28 Juin 2019
Modifié(e) : Edric Ellis le 28 Juin 2019
You've tripped over one of the limitations of for loops nested within parfor. This is described in the doc. The requirement is:
You must define the range of a for-loop nested in a parfor-loop by constant numbers or broadcast variables.
Unfortunately, even indexing a broadcast variable for the range of the for loop is not permitted, so what you need to do is pull out the elements of the size vector outside the loop like this:
function b = fixed(a)
[m,n] = size(a);
b=a;
parfor x=1:m
for y=1:n
b(x,y) = 5;
end
end

Plus de réponses (1)

Matt J
Matt J le 27 Juin 2019
Modifié(e) : Matt J le 27 Juin 2019
I don't know what rule your version violates, but this will work,
parfor x=1:sz(1)
b(x,:) = 5;
end
So will this,
parfor x=1:sz(1)
tmp=nan(1,sz(2));
for y=1:sz(2)
tmp(y)=5;
end
b(x,:) = tmp;
end
I suspect the problem has to do with the fact that b is a Sliced Variable. Sliced variables have some strict rules - some well documented, others not so well documented - about how they can be indexed.
  1 commentaire
Matt J
Matt J le 27 Juin 2019
Modifié(e) : Matt J le 27 Juin 2019
Another version, where tmp's memory is pre-allocated:
buffer=nan(1,sz(2));
parfor x=1:sz(1)
tmp=buffer;
for y=1:sz(2)
tmp(y)=5;
end
b(x,:) = tmp;
end

Connectez-vous pour commenter.

Catégories

En savoir plus sur Parallel for-Loops (parfor) dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by