如何在匿名函数中使用变量? [英] How to use variable in anonymous functions?
问题描述
我试图定义:
f = @(x) d*x
其中d是先前定义的变量,例如d =2.我的目标是让它返回:
where d is a variable defined previously, say d = 2. My goal is to have it return:
@(x) 2*x
但是,MATLAB返回:
However, MATLAB returns:
@(x) d*x
我这样做的原因是在for循环中定义了一系列函数句柄,例如
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?
推荐答案
当您定义已存储:
When you define an anonymous function, variables that are required to fully define the function are stored:
通过使用匿名函数,您还可以从函数工作区中捕获某些变量及其值,并将其存储在句柄中.这些数据值在构造时存储在句柄中,并且只要存在就一直包含在句柄中.每当您随后通过其句柄调用该函数时,MATLAB都会为该函数提供在函数调用的参数列表中指定的所有变量输入
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
您可以在计算机上使用 functions
命令进行验证处理您创建的内容:
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]}
functions
命令提供有关函数句柄的常规信息,以及完整的工作空间,其中包含运行该函数所需的所有局部范围的变量:
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
如预期的那样,第一个句柄q{1}
中的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
第三个:
>> f3 = functions(q{3});
>> f3.workspace{1}
ans =
i: 3
每个手柄存储创建手柄时的i
值..
Each handle stores the value of i
as it was when the handle was created.
这篇关于如何在匿名函数中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!