MATLAB Answers

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

조회 수: 15(최근 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
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개)

Community Treasure Hunt

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

Start Hunting!

Translated by