How to pass input parameter in a function handle
40 次查看(过去 30 天)
显示 更早的评论
I don't know what it is really called so maybe the title of my question can be misleading. Anyway, I am using simulated annealing and I initially set the options as follows
options = saoptimset('DataType', 'custom', 'AnnealingFcn', @PermuteElements, ...
'StallIterLimit',50, 'ReannealInterval',50, 'PlotInterval', 50, 'AcceptanceFcn', @acceptancesa);
then I called simulated annealing with these options and it works fine.
The problem is that I want to have some input parameters for the function PermuteElements(param1,param2,etc) which I will need inside the function. but when I add them in the options
options = saoptimset(..., @PermuteElements(param1,param2,etc), ...);
I get an error. I don't exactly understand the role of the @ in front of the function. So how should I input the parameters to the function? Also, how can I figure out when (and by which function) will the function I made exactly be called during simulated annealing execution?
0 个评论
采纳的回答
Guillaume
2016-6-13
编辑:Guillaume
2016-6-13
Yes, you simply need to wrap your function handle into an anonymous function where the parameters are set. In your case:
%%in your function where param1 is defined and saoptimset is called
param1 = ... %must be set before the anonymous function is created
PermEl = @(optimValues) PermuteElements(param1, optimValues);
%note that changes to param1 from then on will not affect PermEl. param1 value has in effect become a constant in PermEl
options = saoptimset('DataType', 'custom', 'AnnealingFcn', PermEl, ...
'StallIterLimit',50, 'ReannealInterval',50, 'PlotInterval', 50, 'AcceptanceFcn', @acceptancesa);
In effect, the anonymous function is equivalent to creating a function that does
function NewPoint = PermEl(optimValues)
NewPoint = PermuteElements(param1, optimValues) %with param1 defined by the main code
end
except that the above does not work because standard functions have no way of accessing the variables from another function, so param1 would be undefined. Anonymous functions and nested functions can do the capture.
7 个评论
Guillaume
2016-6-13
编辑:Guillaume
2016-6-13
Well, there you go, the optimiser passes two arguments to the function handle so the anonymous function must accept two arguments.
You can either ignore that extra argument in the anonymous function:
PermEl = @(optimValues, ~) PermuteElements(param1, optimValues);
with PermuteElements defined as:
function NewPoint = PermuteElements(param1, optimValues)
or ignore it in PermuteElements:
PermEl = @(optimValues, problemData) PermuteElements(param1, optimValues, problemData)
with PermuteElements defined as:
function NewPoint = PermuteElements(param1, optimValues, ~)
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulated Annealing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!