MATLAB-将函数句柄参数作为句柄传递到另一个函数中
正在做一项涉及遗传算法的作业(很头疼,也很有趣)。我需要能够测试不同的交叉方法和不同的突变方法,以比较它们的结果(我必须为课程撰写的论文的一部分)。因此,我只想将函数名称作为函数句柄传递到 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就会被调用,不带参数,并且非常不高兴。
虽然我知道是的,我可以重写我的代码以使其以不同的方式工作,但我现在很好奇如何使其真正工作。
非常感谢任何帮助。
Working on an assignment involving Genetic Algorithms (loads of headaches, loads of fun). I need to be able to test differing crossover methods and differing mutation methods, to compare their results (part of the paper I have to write for the course). As such, I want to just pass the function names into the Repopulate method, as function handles.
function newpop = Repopulate(population, crossOverMethod, mutationMethod)
...
child = crossOverMethod(parent1, parent2, @mutationMethod);
...
function child = crossOverMethod(parent1, parent2, mutationMethod)
...
if (mutateThisChild == true)
child = mutationMethod(child);
end
...
The key point here is like 3, parameter 3: how do I pass mutationMethod down another level? If I use the @ symbol, I get told:
"mutationMethod" was previously used as a variable,
conflicting with its use here as the name of a function or command.
If I don't use the @ symbol, then mutationMethod gets called, with no parameters, and is quite unhappy.
While I am aware that yes, I could just rewrite my code to make it work differently, I'm now curious as to how to make it actually work.
Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上只是不要使用@符号,而是在调用Repopulate函数时使用它。
示例:
我们称之为:
请参阅 的文档传递函数句柄参数
请注意,您可以通过以下方式检查参数是否为函数句柄:
isa(m,'function_handle')
。因此,您可以通过接受函数句柄和函数名称作为字符串来使您的函数Repopulate更加灵活:现在可以通过两种方式调用:
Actually just dont use the @ symbol, use it when you call the Repopulate function instead.
Example:
which we call as:
Refer to the documentation for Passing Function Handle Arguments
Note you can check if the argument is a function handle by:
isa(m,'function_handle')
. Therefore you can make your function Repopulate more flexible by accepting both a function handle and a function name as a string:which now can be called both ways: