The 3 solutions here are based on building the string, and then using str2func to get the function handle from it. Different implementations for the same functionality, but different readability of the result.
Please note that as highlighted in the comment (thanks to knedlsepp), the recursion order n cannot exceed 32 .
One way is to parse the string definition of the input function and recreate it recursively in the string before converting it to a function handle:
function boo = defFun(foo,n) %% // retrieve the string of the initial function A = functions(foo) ; fstrfull = A.function ; %% // find "input variables" in the header [i1 i2] = regexp(fstrfull, '\(([^\)]+)\)' , 'once' ) ; %// probably can be improved, regexp are not my strong suit strVar = fstrfull(i1+1:i2-1) ; %// => strVar='x' %// to get rid of the parenthesis returned by the regex %% // isolate only the function expression (without the header) ilast = strfind( fstrfull , ')' )+1 ; %// ilast= 5 find the last position of the header fstr = fstrfull(ilast(1):end) ; %// fstr='x.^2' separate only function expression %% // replace "variables" by the expression the desired number of time strFinalFunction = fstr ; for i=2:n strFinalFunction = strrep(strFinalFunction, strVar, ['(' fstr ')'] ) ; end boo = str2func( ['@(' strVar ')' strFinalFunction ] ) ; end
This will give you:
>> boo = defFun(foo,3) boo = @(x)((x.^2).^2).^2
It will work in much more complex cases, if only the input function accepts only one variable.
Alternatively, there is a simpler method that should be even more general. It does not require parsing and, therefore, will work in the potential case when the parsing in the solution above is not performed. The disadvantage is that the definition of a function becomes very opaque.
function boo = defFun2(foo,n) cfoo = {foo} ; %// place the function handle in a cell %// create a string calling the function on itself N number of times strFun = ['@(x) ' repmat('cfoo{1}(',1,n) 'x' repmat(')',1,n) ] ; %// Generate a function handle for the corresponding function boo = str2func( strFun ) ;
But now your function definition is as follows:
>> boo = defFun2(foo,3) boo = @(x)cfoo{1}(cfoo{1}(cfoo{1}(x)))
Much less readable, but it still gives the correct results.
Finally, if readability is critical, you can also include the name of the original function in the function definition, but you have to resort to the controversial eval .
function boo = defFun3(fh,n) fname = inputname(1) ; %// get the name of the function which was called eval( [ fname '={fh};' ] ) ; %// place the function handle in a cell strFun = ['@(x) ' repmat([fname '{1}('],1,n) 'x' repmat(')',1,n) ] ; %// create a string calling the function on itself N number of times boo = str2func( strFun ) ; %// Generate a function handle for the corresponding function
Now this gives you:
boo = defFun3(foo,3) boo = @(x)foo{1}(foo{1}(foo{1}(x))) // <= now you know that boo is the function 'foo' called on itself 3 times.