Search code examples
matlabanonymous-functionfunction-handle

how can I pass an argument to a function handle, but interpret it only on call time?


What I want to do is:

a = 5 
foo = @(x) x+a
a = 3
foo(1) % recieve 4

Instead, I only get 6! On several other tests I ran, I get that a is evaluated when foo is, and and not when foo is called.

For various reasons, I can't work with

foo = @(x,a) x+a

Solution

  • What you are asking to do is not recommended. It will be difficult to debug.

    That said, it can be done using the evalin function to reach out and get the current value of a.

    a=5; 
    foo = @(x)evalin('caller','a')+x; 
    foo(1)  %Returns 6
    
    a=3; 
    foo(1)  %Returns 5
    

    Better (much better!) would be to push the definition of a into an apprpriate data structure or object, and create a function getCurrentValueOfA(). Then you can define foo as

    foo = @(x) getCurrentValueOfA() + x;