Referencing local variable before assignment results in unexpected behavior

Matlab captures by value in anonymous functions:

>> aa = 1;
>> f = @(x) x + aa;
>> f(1)

ans =

     2

>> aa = 2;
>> f(1)   

ans =

     2

However, “normal” inner functions seem to capture-by-reference. The OP’s example translates to:

function n = outer(n)
    function inner()
        n = n + 1;
    end

    inner()
end

returns:

>> outer(3)

ans =

     4

Note that OP’s example cannot be written using anonymous functions as they do not support assignment in their body.

Like Rust, Matlab has two types of “inner” functions. Presumably Rust copied this from Matlab :wink:

3 Likes