【发布时间】:2015-08-20 23:24:42
【问题描述】:
我试图了解如何将函数传递给varfun,我想这适用于arrayfun、cellfun 等。
读取帮助文件,第一个参数应该是:
函数,指定为函数句柄。您可以在文件中定义函数或将其定义为匿名函数。如果 func 对应多个函数文件(即,如果 func 表示一组重载函数),MATLAB 会根据输入参数的类确定调用哪个函数。
所以我尝试使用以下数据:
sampleId = [1 1 1 3 3 3]';
entity = [1 2 3 1 4 5]';
dataTable = table(sampleId, entity)
是的:
varfun(@mean, dataTable)
ans =
mean_sampleId mean_entity
_____________ ___________
2 2.6667
现在,当我匿名定义自己的函数时,就会出现问题,例如:
mymean = @(x){sum(x)/length(x)};
然后抛出错误:
varfun(@mymean, dataTable)
Error: "mymean" was previously used as a variable, conflicting with its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.
然而,如果我不使用 at 符号,我会得到:
varfun(mymean, dataTable)
ans =
Fun_sampleId Fun_entity
____________ __________
[2] [2.6667]
我觉得我一定是在错误的上下文中使用了函数句柄@。任何人都可以启发我吗? (注意,如 cmets 中所述,ans 的显示很奇怪,因为 mymean 返回一个元胞数组。这是一个意外错误。
【问题讨论】:
标签: arrays matlab function anonymous-function