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
?
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With