Why are predefined variables not shown with their value in function handles?

119 views Asked by At

In MATLAB R2020b I have the following code:

f=@(x) x.^2;
y=2;
g=@(x) f(x).*y

and the output is

g = function_handle with value: @(x)f(x).*y

But y = 2, so I would expect the output to be @(x)f.*2. Is this how its supposed to work or a bug? And can I display it as f.*2 rather than f.*y?

1

There are 1 answers

1
Luis Mendo On

When you create the function handle g = @(x) f(x).*y, the current values of the variables f and y get "frozen" into g's definition, as discussed in the documentation.

To inspect the actual values of f and y that g uses, you can call functions as follows:

>> info = functions(g); disp(info)
            function: '@(x)f(x).*y'
                type: 'anonymous'
                file: ''
           workspace: {[1×1 struct]}
    within_file_path: '__base_function'

Specifically, see the workspace field:

>> disp(info.workspace{1})
    f: @(x)x.^2
    y: 2