Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 963
Matt Majic Avatar asked Jun 24 '21 11:06

Matt Majic


People also ask

How do function handles work in MATLAB?

A function handle is a MATLAB® data type that stores an association to a function. Indirectly calling a function enables you to invoke the function regardless of where you call it from. Typical uses of function handles include: Passing a function to another function (often called function functions).


1 Answers

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
like image 172
Luis Mendo Avatar answered Oct 24 '22 11:10

Luis Mendo