how to replace a variable with its value in function handle?

39 views (last 30 days)
I have an application using function handle 'Z' like shown below,
j=[0.1409 0.003490659 0.05493];
for i=1:3
Z{i} = @(u) [1 -u*j(i);0 1];
end
For each 'i' value, 'j' need to be evaluated & placed in the Z{i} function handle.
The results from the above loop will be,
Z{1}= @(u) [1 -u*j(i);0 1];
Z{2}= @(u) [1 -u*j(i);0 1];
Z{3}= @(u) [1 -u*j(i);0 1];
But, the results i expecting to get,
Z{1}= @(u) [1 -u*0.1409;0 1];
Z{2}= @(u) [1 -u*0.003490659;0 1];
Z{3}= @(u) [1 -u*0.05493;0 1];

Accepted Answer

dpb
dpb on 13 Jul 2021
Nope. You get what you want; while the string representation of the function echos the input, any variable(s) inside an anonymous function definition at the time of creation are embedded into the function itself.
When you actually use the above, you get--
>> for i=1:3
Z{i}(i)
end
ans =
1.000000000000000 -0.140900000000000
0 1.000000000000000
ans =
1.000000000000000 -0.006981318000000
0 1.000000000000000
ans =
1.000000000000000 -0.164790000000000
0 1.000000000000000
>>
  3 Comments
dpb
dpb on 16 Jul 2021
Just remember that this also means that changing the definition of the constants in j after the functions are defined has no bearing on the functions--they remain unchanged until redefined.
Steven Lord
Steven Lord on 16 Jul 2021
If you need to see what value the function handle has stored for a particular variable for debugging purposes you can use the functions function.
a = 2;
f = @(x) x.^a
f = function_handle with value:
@(x)x.^a
clear a
% even though a doesn't exist as an independent variable anymore,
% f uses the value of a it stored when f was created
y = f(5)
y = 25
info = functions(f);
info.workspace{1}
ans = struct with fields:
a: 2
Before you ask no, you can't change what value is stored in the function handle without recreating the function handle.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!