Frage

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
War es hilfreich?

Lösung

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;

Andere Tipps

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

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top