Charlie Parker
Charlie Parker

Reputation: 5266

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

For example say I define:

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

is it possible to do

 f.c

or basically get access to the variables within the function handle?

I know I can make objects and structs in Matlab but the issue is that I have a .mat file with a bunch of functions and I would like to see the variables that they are using. In this specific scenario I am trying to avoid having to re-code my stuff by just accessing the variables in matlab but in cases where I don't have the option to re-code it would be nice to just have a way to access the variables/fields that define the function handle. I mean, when I call f(3) it returns 6 so it obviously knows about c somewhere, so how do I get access to that c?

Upvotes: 2

Views: 282

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112769

It is possible, using the function 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, as in your case, one of the fields of F is workspace, which contains information about the variables required by the anonymous function:

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

Upvotes: 9

Related Questions