Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Recursive anonymous function
Date: Mon, 9 Mar 2009 09:50:02 +0000 (UTC)
Organization: University of Sydney
Lines: 59
Message-ID: <gp2ooa$40r$1@fred.mathworks.com>
References: <gp22jh$sif$1@fred.mathworks.com> <gp2in5$pro$1@fred.mathworks.com> <88c4e6f3-3ab8-48cc-9713-d2bcde367719@x13g2000yqf.googlegroups.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1236592202 4123 172.30.248.38 (9 Mar 2009 09:50:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 9 Mar 2009 09:50:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1308310
Xref: news.mathworks.com comp.soft-sys.matlab:523429


Hi Bruno,

I see where you are having issues with iff and its use for recursion.
You are correct that iff will evaluate both conditions and hence there would be no termination for recursion.

I did encounter this issue and make my conditions strings and used eval.
Let me explain my sumval anonymous function so we don't get stuck on the iff.
(Sorry about the length of the explanation)

sumval = @(x,i)(x(i) + eval(char(iff(i==1,'0', 'sumval(x,i-1)'))));

if x = [1 2] and i = 2

Round1
----------
x(i) = x(2) = 2
eval(
      char(
             iff(i==1,'0', 'sumval(x,i-1)')
            )
      )

the iff statement will evaluate:
iff(2==1, '0', 'sumval(x,i-1)') 
=> ((2==1)==true).*'0' + ((2==1)==false).*'sumval(x,i-1)'
=> (0==true).*'0' + (0==false).*'sumval(x,i-1)'
as true = 1 and false = 0
=> (0).*'0' + (1).*'sumval(x,i-1)'
=>     0      + 'sumval(x,i-1)'
now the adding a number to a string produces a vector of values representing the ascii value of the string: [115   117   109   118    97   108    40   120    44   105    45    49    41]

but char([115   117   109   118    97   108    40   120    44   105    45    49    41])
=>  'sumval(x,i-1)'
and eval('sumval(x,i-1)') will cause the second round of recursion

Round2 (i is now 1)
----------
x(i) = x(1) = 1
eval(
      char(
             iff(i==1,'0', 'sumval(x,i-1)')
            )
      )

the iff statement will evaluate:
iff(1==1, '0', 'sumval(x,i-1)') 
=> ((1==1)==true).*'0' + ((1==1)==false).*'sumval(x,i-1)'
=> (1==true).*'0' + (1==false).*'sumval(x,i-1)'
=> (1).*'0' + (0).*'sumval(x,i-1)'
=>     '0'      + 0
=> 48

but char(48) =>  '0'
and eval('0') will end the recursion

hence sumval([1 2], 2) => 2 + 1 + 0 = 3

As I mentioned previously, there is nothing wrong with the recursion itself; 
the problem is that it doesn't work unless declared in an m-file