Parfor variable cannot be classified

1 visualización (últimos 30 días)
Chuck37
Chuck37 el 27 de Jun. de 2019
Editada: Edric Ellis el 28 de Jun. de 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?

Respuesta aceptada

Edric Ellis
Edric Ellis el 28 de Jun. de 2019
Editada: Edric Ellis el 28 de Jun. de 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

Más respuestas (1)

Matt J
Matt J el 27 de Jun. de 2019
Editada: Matt J el 27 de Jun. de 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 comentario
Matt J
Matt J el 27 de Jun. de 2019
Editada: Matt J el 27 de Jun. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Parallel for-Loops (parfor) en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by