为什么在函数句柄中未显示预定义变量及其值?
在 MATLAB R2020b 中,我有以下代码:
f=@(x) x.^2;
y=2;
g=@(x) f(x).*y
输出是
g = function_handle with value: @(x)f(x).*y
但是y = 2,所以我希望输出是@(x)f.*2. 这是它应该如何工作还是错误?我可以将它显示为f.*2而不是f.*y吗?
回答
当您创建函数句柄时g = @(x) f(x).*y,变量的当前值f并y“冻结”到g的定义中,如文档中所述。
要检查的实际值f和y该g用途,您可以拨打functions如下:
>> info = functions(g); disp(info)
function: '@(x)f(x).*y'
type: 'anonymous'
file: ''
workspace: {[1×1 struct]}
within_file_path: '__base_function'
具体见workspace字段:
>> disp(info.workspace{1})
f: @(x)x.^2
y: 2
- Nice. And as Andras commented in chat: "It makes sense that a closed variable that's a 5000-sized matrix will not be substituted". Copying the variable into the function handle allows for lazy copying.