Use of an anonymous functions with additional parameters within a spmd-block
5 views (last 30 days)
Show older comments
Hi community,
this is the first time I couldn't find a solution for my problem by searching the forum, so i decided to post it.
I have a bigger function which uses fminsearch with an anonymous function + additional parameters in a spmd-block. I don't know how to pass these additional Data to my user-fct.
For understanding my problem I generated a minimal-expample. (I know parallel computing makes no sense for this optimization, but my problem is much bigger and takes a long time to calculate):
function [] = start()
for i=1:10
p=i*10;
min = fminsearch(@(x)target(x,p),[10])
end
%function to be minimized
function [val] = target(x,p)
val = (x-p)^2;
end
end
Now, I want to calculate the for-loop in several threads. So I decided to use a spmd-block (also tried parloop,...). I get something like this:
function [] = start()
global p;
x = [];
p = [];
fh_target = @(x)target(x);
matlabpool 5;
spmd
for i=labindex:numlabs:100
p=i*10;
min = fminsearch(fh_target,[10])
end
end
matlabpool close;
%function to be minimized
function [val] = target(x)
val = (x-p)^2;
end
end
But i dont know how to pass the parameter p to the function target via a function-handle that is used by fminsearch. As you can see i tried it with global variables, but this doesn't work.
The parameter is not know before the for-loop or the spmd-block. I'm sorry for my english, but i hope aou understand my problem and somebody can help me.
Best Regards
0 Comments
Accepted Answer
Edric Ellis
on 16 Apr 2012
You need to work around the fact that SPMD blocks cannot call internal functions or define anonymous functions. I would do it like so:
function mn = start()
spmd
% Use a codistributed array to store results
mn = zeros(1,100,codistributor());
% Loop over the elements of the codistributed array in parallel
for i = drange(1:100)
p=i*10;
% SPMD blocks cannot call nested functions, nor declare anonymous functions, so
% call helper function to do optimisation.
mn(i) = doSolve(p,10);
end
end
% Gather the distributed 'mn' back to the CPU.
mn = gather(mn);
end
% Helper function to call fminsearch
function mn = doSolve(p,v)
mn = fminsearch(@(x)target(x,p),v);
end
%function to be minimized
function [val] = target(x,p)
val = (x-p)^2;
end
0 Comments
More Answers (1)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!