object behavior with Octave...

Ben Abbott bpabbott at mac.com
Sat Feb 14 10:34:02 CST 2009


	
On Feb 14, 2009, at 9:54 AM, James Moliere wrote:

>
> looking at the URL
> http://asis.epfl.ch/SCI.MATH/octave-2.0.16/Octave-FAQ_3.html
>
> I don't see the capability below.  Can I assign functions to variables
> in a structure and call them?
>
>
> # simple increment example
> function [ ret ] = tt (a)
>        x.a=a
>        function result = anon(x)
>                x.a = x.a+1
>                result = x
>        endfunction
>        x.increment = @anon
>        ret = x
> endfunction
>
> ... I'd like to do something like this
>
> k = tt(1)
> k.increment(k) % or k.increment() without passing in k
> ... I'd expect an answer of 2.


Your example can be entered at the command line as ...

function result = anon(x)
        x.a = x.a+1;
        result = x;
endfunction
function [ ret ] = tt (a)
        x.a=a;
        x.increment = @anon;
        ret = x;
endfunction

x.a = 0;

anon(x)
ans =
{
   a =  1
}

x = tt(1)
x =
{
   a =  1
   increment =

anon
}

x.increment(x)
ans =
{
   a =  2
   increment =

anon
}

If you try x.increment() it will produce an error, because that is the  
same as calling anon().

Ben


More information about the Help-octave mailing list