Is it possible to iterate over a list of functions in MATLAB? I'm trying to test different functions and this seems like the best way to do it.
Asked
Active
Viewed 6,436 times
2 Answers
24
You can make a cell array of function handles and iterate over that. For example:
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

gnovice
- 125,304
- 15
- 256
- 359
8
If you want to define your own functions it turns out you can do this, following on from gnovice's answer:
funcList = {@(x, y) (x - y), @(x, y) (x + y)}

Dean Barnes
- 2,252
- 4
- 29
- 53
-
1Yup, works for [anonymous functions](http://www.mathworks.com/help/techdoc/matlab_prog/f4-70115.html) too! – gnovice Apr 14 '11 at 21:06