octave-maintainers
[Top][All Lists]
Advanced

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

Re: Nested functions, documented?


From: David Shih
Subject: Re: Nested functions, documented?
Date: Sat, 19 Nov 2011 22:32:16 -0800 (PST)

I ran into the same problem where my Matlab code using nested function is
affected by the variable scope issue.

I have not seen a workaround on the list, so I am providing one here:

You can use anonymous functions with subfunctions to achieve the same effect
as nested functions.
It may even be desired that the programmer explicitly pass the variables
into a subfunction using an anonymous function, so that nested function
variable scopes do not become a mess.


An example:

*Nested version*:

function y = primary_function(x, a, b)

  function z = nested_function(x)
    % nested_function accesses variables a and b from the parent function
    z = x + a + b;
  end

  y = nested_function(x);

end


*Subfunction version (coerced)*:

function y = primary_function(x, a, b)
  y = nested_function(x);
end

function z = sub_function(x)
  % sub_function tries to access variables a and b from the parent function
  % an error will occur, since a and b are not in scope
  z = x + a + b;
end


*Alternative version*:

function y = primary_function(x, a, b)
  y = sub_function( @(x) sub_function(x, a, b) );
end

function z = sub_function(x, a, b)
  % sub_function accesses parameter variables a and b, which are in scope
  z = x + a + b;
end


The nested function will not work in Octave, due to its coercion into a
subfunction and the aforementioned variable scope issue that arises as a
result.

The alternative version will work, since the extra variables are passed by
way of an anonymous function.
One particular use of this is in applying arrayfun(...) for the purpose of
avoiding for-loops:

function Z = powers(x, p)
  % return Z such that the jth column of Z is x raised to the power of each
element of p
  % in other words function POWERS accepts p as an array and subfunction
POWER accept p as a scalar

  % use anonymous function to pass x to power
  Z = arrayfun( @(k) power(x, k), p );
end

function Z = power(x, p)
  % A simple sub-function, which can conceivable be much more complex
  Z = x .^ p;
end


--
View this message in context: 
http://octave.1599824.n4.nabble.com/Nested-functions-documented-tp3326455p4088066.html
Sent from the Octave - Maintainers mailing list archive at Nabble.com.


reply via email to

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