Nested cellfun in parfor loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Ida
el 8 de Jun. de 2017
Comentada: Ida
el 12 de Jun. de 2017
Hello,
I'm trying to set up a function for cells using cellfun inside a parfor loop. A simplified example seen below:
%Main function
function main
M = rand(100,100);
N = rand(100,100);
const = rand(100,1); %Does not change during parfor loop
parfor i=1:size(M,2)
X = num2cell( M(:,i),1 );
Y = num2cell( N(:,i),1 );
Z = cellfun(@(x,y) nestedFunc(const,x,y), X,Y, 'uniformoutput',0 );
end
%Nested function
function z = nestedFunc(const,x,y)
%Do a bunch of stuff...
end
end
However, using
Z = cellfun(@(x,y) nestedFunc(const,x,y), X,Y, 'uniformoutput',0 );
is not allowed inside parfor: " The nested function 'nestedFunc' cannot be called within a PARFOR loop".
I've read that you can use the feval and the handle to the function to get around this, like this (from Matlab documentation):
function A = pfeg
function out = nfcn(in)
out = 1 + in;
end
fcn = @nfcn;
parfor idx = 1:10
A(idx) = feval(fcn, idx);
end
end
I do not manage to do this when my function is a cellfun however. I can get around the issue by defining nestedFunc in a separate .m file, but I would prefer if it could be done inside the function itself. (Also, I don't know if calling a separate function takes more time compared to a nested function?)
Can anyone please advice me? Thank you!
0 comentarios
Respuesta aceptada
Edric Ellis
el 9 de Jun. de 2017
Here's some code that I tried combining using nested functions together with parfor and cellfun:
function out = pfeg
const = 7;
function out = nFcn(x, offset)
out = x + offset;
end
fcnHandle = @(in) nFcn(in, const);
parfor idx = 1:10
out{idx} = cellfun(fcnHandle, num2cell(1:idx));
end
end
This works as expected. Note that using nested functions inside parfor is somewhat risky - because each worker gets its own copy of "uplevel variables" - i.e. those variables shared between parent and nested function.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!