Parfor variable cannot be classified

1 view (last 30 days)
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?

Accepted Answer

Edric Ellis
Edric Ellis on 28 Jun 2019
Edited: Edric Ellis on 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

More Answers (1)

Matt J
Matt J on 27 Jun 2019
Edited: Matt J on 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 Comment
Matt J
Matt J on 27 Jun 2019
Edited: Matt J on 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

Sign in to comment.

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!