10

从事涉及遗传算法的任务(大量的头痛,大量的乐趣)。我需要能够测试不同的交叉方法和不同的变异方法,以比较它们的结果(我必须为课程写的部分论文)。因此,我只想将函数名称作为函数句柄传递给 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
  ...

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

"mutationMethod" was previously used as a variable,
 conflicting with its use here as the name of a function or command.

如果我不使用@ 符号,那么mutationMethod 会被调用,没有参数,并且非常不高兴。

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

任何帮助是极大的赞赏。

4

1 回答 1

13

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

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

function y = fun2(b,n)
    y = n(b);
end

我们称之为:

> fun1([1 2 3], @sum)
6

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


请注意,您可以通过以下方式检查参数是否为函数句柄: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

现在可以两种方式调用:

fun1([1 2 3], @sum)
fun1([1 2 3], 'sum')
于 2009-10-22T14:51:16.440 回答