Parfor variable cannot be classified

2 visualizzazioni (ultimi 30 giorni)
Chuck37
Chuck37 il 27 Giu 2019
Modificato: Edric Ellis il 28 Giu 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?

Risposta accettata

Edric Ellis
Edric Ellis il 28 Giu 2019
Modificato: Edric Ellis il 28 Giu 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

Più risposte (1)

Matt J
Matt J il 27 Giu 2019
Modificato: Matt J il 27 Giu 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 Commento
Matt J
Matt J il 27 Giu 2019
Modificato: Matt J il 27 Giu 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

Accedi per commentare.

Categorie

Scopri di più su Parallel for-Loops (parfor) in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by