help-octave
[Top][All Lists]
Advanced

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

Re: Functions inhereting variables


From: Jaroslav Hajek
Subject: Re: Functions inhereting variables
Date: Fri, 19 Nov 2010 09:11:00 +0100

On Fri, Nov 19, 2010 at 3:09 AM, Mike B. <address@hidden> wrote:
> Hi all,
>
> Is it possible to define a function which `inherits' variables from the scope 
> it was called from without explicity passing them for example:
>
> function out = f( x )
>   out = x + a + b;
> endfunction
>
> and in the main code:
> a=1
> b=2
> f( 3 )
> would give 6
>
> Anonymous functions can inherit variables but they seem limited to simple 
> 1-line codes.
>
> Thanks,
> Mike.
>
>

If you won't fit on a single line, I strongly recommend you to make a
regular function (may be private or subfunction) with extra params and
then create an anonymous function that binds the parameters to your
values:

function out = fp(x, a, b)
  out = x + a + b;
endfunction

...

a = 1; b = 2;
f = @(x) fp(x, a, b);

This is the best programming practice, because it makes clearly
visible which vars are inherited and which aren't. And finally, Octave
3.3.53 (or 52+) can, under favorable circumstances, optimize away the
extra overhead of the anonymous function call, giving you essentially
the same performance as if you called the function directly:
http://octave.1599824.n4.nabble.com/anonymous-functions-optimization-wanted-for-3-4-0-tt2534161.html

This is much better than global vars or evalin. I recommend you only
use globals if you *really need* to modify them (because Octave has no
pointers) and only use evalin/assignin if you're about to commit
suicide.
Matlab also has nested funcs for this; Octave doesn't support them
yet. Even if it does in the future, I'd recommend anyone to stick with
this approach, it's just cleaner.

regards



reply via email to

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