在MATLAB中迭代一个函数向量。

19
在MATLAB中是否可以迭代遍历函数列表?我正在尝试测试不同的函数,这似乎是最好的方法。
2个回答

24
你可以制作一个存储函数句柄的单元数组并对其进行迭代。例如:

你可以制作一个单元 数组,其中包含函数句柄,然后对其进行迭代。

vec = 1:5;                            % A sample vector of values
fcnList = {@max, @min, @mean};        % Functions to apply to the vector
nFcns = numel(fcnList);               % Number of functions to evaluate
result = zeros(1, nFcns);             % Variable to store the results
for iFcn = 1:nFcns
  result(iFcn) = fcnList{iFcn}(vec);  % Get the handle and evaluate it
end

8

如果您想定义自己的函数,那么您可以像gnovice的回答一样这样做:

funcList = {@(x, y) (x - y), @(x, y) (x + y)}

1
是的,这也适用于匿名函数! - gnovice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接