MATLAB stores variables along with anonymous functions. Here is an example of how this works from the documentation.
Variables in the Expression:
Function handles can store not only an expression, but also variables that the expression requires for evaluation.
For example, create a function handle to an anonymous function that requires coefficients a, b, and c.
a = 1.3; b = .2; c = 30; parabola = @(x) a*x.^2 + b*x + c;
Because a, b, and c are available at the time you create parabola, the function handle includes those values. The values persist within the function handle even if you clear the variables:
clear a b c x = 1; y = parabola(x) y = 31.5000
Supposedly, the values of a b and c are stored with the function even when it's saved and reloaded from a mat file. In practice, I've found that these values do not persist, especially if the code that originally created the function is edited.
Is there a way to define the function handle in terms of the numeric values of the variables? I would like something of the form
>> a = 1.3;
>> b = .2;
>> c = 30;
>> parabola = @(x) a*x.^2 + b*x + c
parabola = @(x) a*x.^2+b*x+c
>> parabola2 = forceEval(parabola)
parabola2 = @(x) 1.3*x.^2+.2x+30
EDIT: Perhaps my problem is with the file association, but when I edit the file that I originally defined the anonymous function in, I get an error that looks like:
Unable to find function @(ydata)nr/(na*dt)*normpdf(ydata,mu(j),s(j))./normpdf(ydata,mu_a(j),s_a(j)) within C:...\mfilename.m. (where I've changed the name of my mfile to mfilename)
My usual solution to this kind of stuff has been to use func2str() to remove the file dependency, but this also strips out the workspace information including the parameter values. So I would like to force all the parameters to take on their numerical values in the function definition.
The values are stored in the function. As I've demonstrated in different answers before, you can check this with the functions
command:
>> a = 1.3; b = .2; c = 30;
>> parabola = @(x) a*x.^2 + b*x + c;
>> x = 1;
>> y = parabola(x)
y =
31.5
>> clear a b c
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '@(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
Even when you save the handle to disk:
>> save parabolaFun.mat parabola
>> clear parabola a b c
>> load parabolaFun.mat parabola
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '@(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
And you can simplify the creation of a parabola handle like this:
function p = makeParabola(a,b,c)
p = @(x) a*x.^2 + b*x + c;
end
There are certain caveats:
You can save and load function handles in a MAT-file using the MATLAB® save and load functions. If you load a function handle that you saved in an earlier MATLAB session, the following conditions could cause unexpected behavior:
- Any of the files that define the function have been moved, and thus no longer exist on the path stored in the handle.
- You load the function handle into an environment different from that in which it was saved. For example, the source for the function either does not exist or is located in a different folder than on the system on which the handle was saved.
In both of these cases, the function handle is now invalid because it is no longer associated with any existing function code. Although the handle is invalid, MATLAB still performs the load successfully and without displaying a warning. Attempting to invoke the handle, however, results in an error.
Hence, if you create the handle from a file-backed function (not a script, that's OK), and then modify or delete the file, the handle will become invalid.
Anonymous functions capture the values of all variables involved in the expression. If you want to see the environment workspace captured, use functions
as @chappjc showed in his answer.
Now you gotta be careful about the type of variables used in the anonymous function (think value-type vs. handle-type).
All native types (numerics, logicals, structs, cells, etc..) are captured by-value not by-reference. Example:
x = magic(4);
f = @() x; % captures matrix x
x(1) = 1 % modify x
xx = f() % change not reflected here
Compare that to using handle-class types (e.g containers.Map
):
x = containers.Map('KeyType','char', 'ValueType','double');
f = @() x; % captures handle-class object x
x('1') = 1; % modify map
keys(x) % changed
keys(f()) % also changed!
f() == x % compare handle equality, evaluates to true
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