Amir Sagiv
Amir Sagiv

Reputation: 386

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

Upvotes: 2

Views: 72

Answers (3)

Pursuit
Pursuit

Reputation: 12345

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;

Upvotes: 1

chappjc
chappjc

Reputation: 30579

You can check the value of stored data with the functions command:

>> a = 5 
foo = @(x) x+a
a =
     5
foo = 
    @(x)x+a
>> handleInfo = functions(foo)
handleInfo = 
     function: '@(x)x+a'
         type: 'anonymous'
         file: ''
    workspace: {[1x1 struct]}
>> handleInfo.workspace{1}
ans = 
    a: 5

Upvotes: 1

DWilches
DWilches

Reputation: 23016

When you create an anonymous function in Matlab it stores the current value of any variables that it needs and that are not part of its inputs.

So, when you created foo like this:

a = 5
foo = @(x) x+a

It stored the equivalent of this:

foo = @(x) x+5

Even if you change later the value of a the value of that constant stored inside foowon't change.

If in the other hand you want the value of a to change, you have to accept a as a parameter of the function as well.

Source: http://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html

Upvotes: 1

Related Questions