#581 Undefined variable error

v4.1 (minor)
open
Samit Basu
M-Files (31)
5
2014-04-22
2013-02-09
Vasilis Nicolaou
No

While having nested functions, in a parent function, they don't recognise the variables defined in the parent one. Matlab does that and it is really annoying since neither declaring them global works. Please fix.

Discussion

  • Samit Basu
    Samit Basu
    2013-03-31

    • assigned_to: nobody --> samitbasu
     
  • Samit Basu
    Samit Basu
    2013-03-31

    Please post an example.

     
  • Example
    Function f=my_function(input)
    constant = 5
    Function g=eqation(init)
    do something with constant

     
  • Tunococ
    Tunococ
    2014-04-22

    I just encountered this too. MATLAB and Octave allow nested functions to access variables in the scope of the enclosing function. This makes it possible to define, for example, a non-anonymous function that relies on some input arguments of the enclosing function. For example, the following function is supposed to add scalar to each entry of X:

    function Y = addscalar(X, scalar)
    
      function z = addentry(x)
        z = x + scalar;
      end
    
      Y = arrayfun(@addentry, X);
    
    end
    

    FreeMat will complain that scalar is unknown in the scope of addentry. This works, however, if I define addentry as an anonymous function:

    function Y = addscalar(X, scalar)
    
      Y = arrayfun(@(x) x + scalar, X);
    
    end
    

    Of course the functionality of addscalar itself is not important here as + already operates this way.

    The thing is sometimes the function of which the handle will be passed as an argument to another function cannot be written as an anonymous function.