フィルターのクリア

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

14 ビュー (過去 30 日間)
Vinothkumar Sethurasu
Vinothkumar Sethurasu 2021 年 7 月 13 日
コメント済み: Steven Lord 2021 年 7 月 16 日
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];

採用された回答

dpb
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
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
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
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by