Parfor variable cannot be classified

2 Ansichten (letzte 30 Tage)
Chuck37
Chuck37 am 27 Jun. 2019
Bearbeitet: Edric Ellis am 28 Jun. 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?

Akzeptierte Antwort

Edric Ellis
Edric Ellis am 28 Jun. 2019
Bearbeitet: Edric Ellis am 28 Jun. 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

Weitere Antworten (1)

Matt J
Matt J am 27 Jun. 2019
Bearbeitet: Matt J am 27 Jun. 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 Kommentar
Matt J
Matt J am 27 Jun. 2019
Bearbeitet: Matt J am 27 Jun. 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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Parallel for-Loops (parfor) finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by