how to replace a variable with its value in function handle?
12 次查看(过去 30 天)
显示 更早的评论
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];
0 个评论
采纳的回答
dpb
2021-7-13
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 个评论
dpb
2021-7-16
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
2021-7-16
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
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)
info = functions(f);
info.workspace{1}
Before you ask no, you can't change what value is stored in the function handle without recreating the function handle.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!