Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Recursive anonymous function
Date: Mon, 9 Mar 2009 03:32:01 +0000 (UTC)
Organization: University of Sydney
Lines: 48
Message-ID: <gp22jh$sif$1@fred.mathworks.com>
Reply-To: <HIDDEN>
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 1236569521 29263 172.30.248.35 (9 Mar 2009 03:32:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 9 Mar 2009 03:32:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1308310
Xref: news.mathworks.com comp.soft-sys.matlab:523396


Hello,

I have been playing with anonymous functions.
As you cannot have if or while statements, I am trying to see if I can emulate them.

An if statement can be done with boolean logic
(I believe this construct is called a binary switch)
iff = @(cond,t,f)((cond==true).*t + (cond==false).*f);

As with a m-file version of iff, the downside is that both the true and false conditions need to be evaluated.

Now my thoughts for doing a while loop is to use recursion.
my example program is
function res = sumval(x,i)
    if i == 1
       res = x(i);
    else
       res = x(i) + sumval(x,i-1);
    end
end

thus sumval(1:5,5) => 15

As an anonymous function I have got:
sumval = @(x,i)(x(i) + eval(char(iff(i==1,'0', 'sumval(x,i-1)'))));

Now my problem is that the anonymous function works inside an m-file

eg:

function res = sumv()
    iff = @(cond,t,f)((cond==true).*t + (cond==false).*f);
    sumval = @(x,i)(x(i) + eval(char(iff(i==1,'0', 'sumval(x,i-1)'))));
    res = sumval(1:5,5);
end

sumv() => 15

but just running the 3 statements in the workspace causes an error:
??? Error using ==> eval
Undefined function or method 'sumval' for input arguments of type 'double'.

This tells me that the scope of the sumval function does not include the workspace scope. However, even if I define iff and sumval to be global, the error still happens.

How can I make a global anonymous function which is recursive?
That is: I want to define an anonymous function in the workspace and have it be globally accessable to itself

Brandon