need function handle test run in Matlab

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

need function handle test run in Matlab

John W. Eaton
Administrator
Given the attached functions anonfcn.m and nestfcn.m, What does a
current version of Matlab do for the following code?

   afh = anonfcn (13)
   afh ('a')
   afh ('b')
   nfh = nestfcn (42)
   nfh ('a')
   nfh ('b')

Could someone please run this test and post the results here?

Thanks,

jwe


anonfcn.m (73 bytes) Download Attachment
nestfcn.m (114 bytes) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: need function handle test run in Matlab

nrjank
diary attached.  Matlab 2018b



On Sat, Mar 16, 2019 at 9:28 PM John W. Eaton <[hidden email]> wrote:

>
> Given the attached functions anonfcn.m and nestfcn.m, What does a
> current version of Matlab do for the following code?
>
>    afh = anonfcn (13)
>    afh ('a')
>    afh ('b')
>    nfh = nestfcn (42)
>    nfh ('a')
>    nfh ('b')
>
> Could someone please run this test and post the results here?
>
> Thanks,
>
> jwe
>

fntests.txt (2K) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: need function handle test run in Matlab

John W. Eaton
Administrator
On 3/16/19 9:51 PM, Nicholas Jankowski wrote:
> diary attached.  Matlab 2018b
>
 >    afh = anonfcn (13)
 >
 >    afh =
 >
 >        @(s)eval(s)
 >
 >     afh ('a')
 >
 >     Undefined function or variable 'a'.
 >
 >    afh ('b')
 >
 >     Undefined function or variable 'b'.
 >
 >    nfh = nestfcn (42)
 >
 >    nfh =
 >
 >        @nestfcn/nst
 >
 >    nfh ('a')
 >
 >     ans =
 >
 >        42
 >
 >     nfh ('b')
 >
 >     ans =
 >
 >        16     2     3    13
 >         5    11    10     8
 >         9     7     6    12
 >         4    14    15     1


Thanks.

So even though anonymous functions can capture values from the
surrounding context, they are not equivalent to nested functions, which
apparently have full access to the parent workspaces even when the
variables are not explicitly referenced.  I was hoping they would be
equivalent (then the internal representation could be essentially
identical; the only difference would be the syntax for parsing) but half
expecting that they would be different because anonymous functions came
well before nested functions.  I believe Octave gets this behavior right
but there is room for improvement in thm implementation.

jwe