Issues with nested functions

| categories: uncategorized | View Comments

nested_function_issues

Contents

Issues with nested functions

John Kitchin

Nested functions are great for passing lots of information between functions conveniently. But, there are some gotchas to be wary of!

function main

a typical nested function use

It is common to define several parameters, and then to use them inside a nested function

a = 4;
b = 3;

    function y = f1(x)
        y = a + b*x;
    end

f1(2)
ans =

    10

classic example of a potential problem

Nested functions share the same namespace as the main function, which means you can change the value of a variable in the main function in the nested function. This does not happen with subfunctions.

i = 5 % initial value of i
    function y = f2(x)
        % nested function that uses a and b from above, and uses an
        % internal loop to compute a value of y.
        y = 0;
        for i=1:10  % this is going to change the value of i outside this function
            y = y + a*b + i;
        end
    end

f2(2)
i % note i = 10 now
i =

     5


ans =

   175


i =

    10

This kind of behavior can be very difficult to debug or even know is a problem! you have to be aware that it is an issue when using nested functions.

subfunctions

subfunctions do not share namespaces, so you can reuse variable names. This can prevent accidental variable value changes, but, you have to put the variable information into the subfunction

i = 5
f3(2)
i % note that the value of i has not been changed here.
i =

     5


ans =

   175


i =

     5

end

function y = f3(x)
% subfunction that uses a and b from above, and uses an internal loop
% to compute a value of y.
a = 4;
b = 3;
y = 0;
for i=1:10  % this is going to change the value of i outside this function
    y = y + a*b + i;
end
end

% categories: basic
blog comments powered by Disqus