I know that this is not what anonymous functions are made for, but just as a puzzle I tried to make a recursive function via anonymous functions. The prototype of recursive functions obviously is the factorial function. The problem is that it is difficult to make a case distinction within the anonymous functions. What I managed to do so far is following:
f=@(cn,n,f)eval('if n>1; f(cn*n,n-1,f);else;ans=cn;end');
f=@(n)f(1,n,f);
Or alternatively:
f=@(cn,n,f)eval('if n>1; f(cn*n,n-1,f);else;disp(cn);end');
f=@(n)f(1,n,f);
What is not very satisfactory is that you still cannot use this function when directly assigning, a=f(3)
still produces an error, since eval
does not get a value.
So my question is, can you actually do a recursive function via anonymous functions that e.g. calculates factorial in a way that allows e.g. a=f(3)
with relying only on native matlab functions (or functions you can create in the command line, as I did in my example)?
PS: I know this does not have any practical use, it is just a challenge on how much you can bend and abuse Matlab's syntax.