Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variable in anonymous functions?

Tags:

matlab

I was trying to define:

f = @(x) d*x

where d is a variable defined previously, say d = 2. My goal is to have it return:

@(x) 2*x

However, MATLAB returns:

@(x) d*x

The reason I was doing this was to define a series of function handles in a for loop, e.g.

q = cell(n, 1);
for i = 1:n
    q{i} = @(y) sum(y(1:i));
end

Is it possible to define an array of function handles that use the indices in the anonymous function definitions?

like image 435
MoW Avatar asked Jan 11 '23 01:01

MoW


2 Answers

Its correct. When you define f = @(x) d*x matlab will look for d in local scope. Since d was 2 at the time of function definition, your function f will be effectively 2*x. Even if you change value of d later on, e.g. d=10, the 'f' function will still use 2.

Here is an example:

d = 2;

f = @(x) d*x;    

f(2) % gives 4;

d = 10;

f(2) % gives 4 again. matlab will 'remember' that d was 2 at the time of 
     % f function definition 
like image 188
Marcin Avatar answered Jan 17 '23 17:01

Marcin


When you define an anonymous function, variables that are required to fully define the function are stored:

By using anonymous functions, you can also capture certain variables and their values from the function workspace and store them in the handle. These data values are stored in the handle at the time of its construction, and are contained within the handle for as long as it exists. Whenever you then invoke the function by means of its handle, MATLAB supplies the function with all variable inputs specified in the argument list of the function call

You can verify this with the functions command on the handles you created:

>> n=3;
>> for i = 1:n, q{i} = @(y) sum(y(1:i)); end
>> f1 = functions(q{1})
f1 = 
     function: '@(y)sum(y(1:i))'
         type: 'anonymous'
         file: ''
    workspace: {[1x1 struct]}

The functions command gives general information about the function handle, as well as the full workspace containing all locally scoped variables required to run the function:

>> f1.workspace{1}
ans = 
    i: 1

As expected, i is 1 in the first handle q{1}. Now, the second handle:

>> f2 = functions(q{2});
>> f2.workspace{1}
ans = 
    i: 2

And the third:

>> f3 = functions(q{3});
>> f3.workspace{1}
ans = 
    i: 3

Each handle stores the value of i as it was when the handle was created.

like image 29
chappjc Avatar answered Jan 17 '23 19:01

chappjc