Path: news.mathworks.com!not-for-mail
From: "Kenneth Eaton" <Kenneth.dot.Eaton@cchmc.dot.org>
Newsgroups: comp.soft-sys.matlab
Subject: Recursive anonymous function
Date: Mon, 9 Mar 2009 14:02:01 +0000 (UTC)
Organization: Cincinnati Children's Hospital Research Center
Lines: 22
Message-ID: <gp37gp$s3l$1@fred.mathworks.com>
References: <gp22jh$sif$1@fred.mathworks.com>
Reply-To: "Kenneth Eaton" <Kenneth.dot.Eaton@cchmc.dot.org>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1236607321 28789 172.30.248.35 (9 Mar 2009 14:02:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 9 Mar 2009 14:02:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1165924
Xref: news.mathworks.com comp.soft-sys.matlab:523476


Brandon,

Trying to perform recursion with anonymous functions seems very odd. However, I understand your curiosity to try it out anyway. Here's an anonymous function formulation I came up with for computing factorials. It actually uses 2 anonymous functions, one for each "branch" of the recursion:

>> fact = @(val,branchFcns) val*feval(branchFcns{(val == 1)+1},val-1,branchFcns);
>> returnOne = @(val,branchFcns) 1;
>> branchFcns = {fact returnOne};
>> fact(4,branchFcns)

ans =

    24

>> fact(5,branchFcns)

ans =

   120

As you can see, it works. It is, however, Rube-Goldberg-esque. =)

Ken