是否可以在 Matlab 中访问函数句柄内的变量?

Is it possible to get access to variables inside function handles in Matlab?

比如我定义:

c=3;
f = @(x) x + c;

是否可以做

 f.c

或者基本上可以访问函数句柄中的变量?

我知道我可以在 Matlab 中创建对象和结构,但问题是我有一个包含大量函数的 .mat 文件,我想查看它们正在使用的变量。在这个特定的场景中,我试图通过访问 matlab 中的变量来避免重新编码我的东西,但是在我没有重新编码的选项的情况下,最好有一种方法来访问variables/fields 即定义函数句柄。我的意思是,当我调用 f(3) 它 returns 6 时,它显然知道某个地方的 c,那么我如何才能访问那个 c

有可能,使用函数 functions. Calling F = functions(f) returns a struct F with information about the function with handle f. When f is a handle to an anonymous function,如您的情况,F 的字段之一是 workspace,其中包含有关匿名所需变量的信息功能:

>> c = 3;
>> f = @(x) x + c;
>> F = functions(f)
F = 
            function: '@(x)x+c'
                type: 'anonymous'
                file: ''
           workspace: {[1x1 struct]}
    within_file_path: '__base_function'
>> F.workspace{1}.c
ans =
     3