help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: function handles & closures - porting from matlab


From: Ian Rickard
Subject: Re: function handles & closures - porting from matlab
Date: Wed, 29 Jul 2009 10:35:16 -0700

Sorry, yeah, should have provided that info:

octave 3.2.1.

Expected:
> a = gen_poly_funs(2);
> a{1}(2)
ans =  1
> a{3}(2)
ans =  4

observed:
octave-3.2.0:26> a = gen_poly_funs(2);
octave-3.2.0:27> a{1}(2)
ans =  4
octave-3.2.0:28> a{3}(2)
ans =  4

However, in looking at how scoping works, I discovered the problem: I
had n used as different variables within what octave treats as the
same scope.  Changing it as follows works:

function fns = gen_poly_funs(n)
    fns = arrayfun(@term,0:n,'UniformOutput',false);
end

function f = term(n)
        f = @(x)x.^n
end

This creates a separate scope for each returned function handle, so
they each have a unique value of n.

On Wed, Jul 29, 2009 at 10:03 AM, John W. Eaton<address@hidden> wrote:
> On 29-Jul-2009, Ian Rickard wrote:
>
> | I'm currently trying to port a code base from matlab to octave.  It
> | uses the following pattern extensively:
> |
> | function fns = gen_poly_funs(n)
> |     fns = arrayfun(@(n)(@(x)x.^n),0:n,'UniformOutput',false);
> | end
> |
> | As far as I can tell this pattern breaks in Octave, as there appears
> | to be a single global value for n.  Is there an easy way to mimic
> | matlab's behavior where the n is unique for each of the returned
> | function handles?
>
> What version of Octave are you using?
>
> What result are you expecting?
>
> Here is what I see when using Octave 3.2.0:
>
>  octave3.2:1> function fns = gen_poly_funs(n)
>  >     fns = arrayfun(@(n)(@(x)x.^n),0:n,'UniformOutput',false);
>  > end
>  octave3.2:2> gen_poly_funs (2)
>  ans =
>
>  {
>    [1,1] =
>
>  @(x) x .^ n
>
>    [1,2] =
>
>  @(x) x .^ n
>
>    [1,3] =
>
>  @(x) x .^ n
>
>  }
>
> Is that not correct?
>
> In any case, if you think you've found a bug in Octave, then  please
> send a complete bug report to the address@hidden list.  To find out
> what information to include in your bug report so that it is useful,
> please read http://www.octave.org/bugs.html.
>
> jwe
>



reply via email to

[Prev in Thread] Current Thread [Next in Thread]