MATLAB-将函数句柄参数作为句柄传递给另一个函数

9 matlab nested-function function-handle genetic-algorithm

从事涉及遗传算法的任务(头痛负荷,有趣的负担).我需要能够测试不同的交叉方法和不同的基因突变的方法,来比较其结果(本文我必须写在课程的一部分).因此,我想将函数名称作为函数句柄传递给Repopulate方法.

function newpop = Repopulate(population, crossOverMethod, mutationMethod)
  ...
  child = crossOverMethod(parent1, parent2, @mutationMethod);
  ...

function child = crossOverMethod(parent1, parent2, mutationMethod)
  ...
  if (mutateThisChild == true)
    child = mutationMethod(child);
  end
  ...
Run Code Online (Sandbox Code Playgroud)

这里的关键点是3,参数3:如何将mutationMethod传递到另一个级别?如果我使用@符号,我会被告知:

"mutationMethod" was previously used as a variable,
 conflicting with its use here as the name of a function or command.
Run Code Online (Sandbox Code Playgroud)

如果我不使用@符号,那么在没有参数的情况下调用mutationMethod,并且非常不满意.

虽然我知道是的,但我可以重写我的代码以使其工作方式不同,我现在很好奇如何让它实际工作.

任何帮助是极大的赞赏.

Amr*_*mro 13

实际上只是不使用@符号,而是在调用Repopulate函数时使用它.例:

function x = fun1(a,m)
    x = fun2(a,m);
end

function y = fun2(b,n)
    y = n(b);
end
Run Code Online (Sandbox Code Playgroud)

我们称之为:

> fun1([1 2 3], @sum)
6
Run Code Online (Sandbox Code Playgroud)

请参阅传递函数句柄参数的文档


请注意,您可以检查,如果该参数是一个函数句柄:isa(m,'function_handle').因此,通过将函数句柄和函数名称都接受为字符串,可以使函数Repopulate更加灵活:

function x = fun(a,m)
    if ischar(m)
        f = str2func(m);
    elseif isa(m,'function_handle')
        f = m;
    else
        error('expecting a function')
    end
    x = fun2(a,f);
end
Run Code Online (Sandbox Code Playgroud)

现在可以双向调用:

fun1([1 2 3], @sum)
fun1([1 2 3], 'sum')
Run Code Online (Sandbox Code Playgroud)