1 ## Copyright (C) 2007 Muthiah Annamalai <muthiah.annamalai@mavs.uta.edu>
2 ## Copyright (C) 2012 Carnë Draug <carandraug+dev@gmail.com>
4 ## This program is free software; you can redistribute it and/or modify it under
5 ## the terms of the GNU General Public License as published by the Free Software
6 ## Foundation; either version 3 of the License, or (at your option) any later
9 ## This program is distributed in the hope that it will be useful, but WITHOUT
10 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 ## You should have received a copy of the GNU General Public License along with
15 ## this program; if not, see <http://www.gnu.org/licenses/>.
18 ## @deftypefn {Function File} @var{result} = {} match ( @var{fun_handle}, @var{iterable} )
19 ## match is filter, like Lisp's ( & numerous other language's ) function for
20 ## Python has a built-in filter function which takes two arguments,
21 ## a function and a list, and returns a list. 'match' performs the same
22 ## operation like filter in Python. The match applies the
23 ## function to each of the element in the @var{iterable} and collects
24 ## that the result of a function applied to each of the data structure's
25 ## elements in turn, and the return values are collected as a list of
26 ## input arguments, whenever the function-result is 'true' in Octave
27 ## sense. Anything (1,true,?) evaluating to true, the argument is
28 ## saved into the return value.
30 ## @var{fun_handle} can either be a function name string or a
31 ## function handle (recommended).
33 ## Typically you can use it as,
35 ## match(@@(x) ( x >= 1 ), [-1 0 1 2])
38 ## @seealso{reduce, cellfun, arrayfun, cellfun, structfun, spfun}
41 function rval = match (fun_handle, data)
47 if (isa (fun_handle, "function_handle"))
49 elseif (ischar (fun_handle))
50 fun_handle = str2func (fun_handle);
52 error ("fun_handle must either be a function handle or the name of a function");
60 if fun_handle(data{idx}), rval = [rval, data{idx}]; endif
62 elseif (ismatrix (data))
65 if fun_handle(data(idx)), rval = [rval, data(idx)]; endif
68 error("data must either be a cell array or matrix");
72 %!assert(match(@(x) mod(x,2),1:10),[1:2:10],0)
73 %!assert(match(@sin,1:10),[1:10],0)
74 %!assert(match(@(x) strcmp('Octave',x),{'Matlab','Octave'}),{'Octave'},0)
75 %!assert(match(@(x) (x>0), [-10:+10]),[1:10],0)