How to use a variable in anonymous functions?

I tried to determine:

f = @(x) d*x

where d is the variable defined earlier, say d = 2. My goal is to return it:

@(x) 2*x

However, MATLAB returns:

@(x) d*x

The reason I did this was to define a series of function handles in a for loop, for example.

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 descriptors that use indexes in the definitions of anonymous functions?

+4
source share
2 answers

When you define an anonymous function, the variables that are needed to fully define the function are saved :

, . , . , , MATLAB ,

functions :

>> 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]}

functions , , - , :

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

, i 1 q{1}. :

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

:

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

i, .

+4

. f = @(x) d*x, matlab d . d 2 , f 2*x. d , . d=10 'f' - 2.

:

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 
+5

Source: https://habr.com/ru/post/1530362/


All Articles