フィルターのクリア

how to use function handles

6 ビュー (過去 30 日間)
G A
G A 2021 年 8 月 29 日
コメント済み: G A 2021 年 8 月 31 日
Instead of the following, I want to use function handles and move if-statments out of the loop:
for n=1:10
if a==0
A = function2(n,a,b);
else
A = function1(n,a,b,c,d);
end
end
function A = function1(n,a,b,c,d)
A = n+a+b+c+d; % here it can be any expression
end
function A = function2(n,a,b)
A = n*a*b; % here it can be any expression
end
moving if-statement outside of the loop and using handles:
if a==0
func = @function2;
else
func = @function1;
end
and then I can solve my problem in two ways as
for n=1:10
A = func(n,a,b,c,d);
end
function A = function1(n,a,b,c,d)
A = n+a+b+c+d;
end
function A = function2(n,a,b,~,~)
A = n*a*b;
end
or as
for n=1:10
A = func(n,a,b,c,d)
end
function A = function1(n,a,varargin)
b = varargin{1};
c = varargin{2};
d = varargin{3};
A = n+a+b+c+d;
end
function A = function2(n,a,varargin)
b = varargin{1};
A = n*a*b;
end
Is there any more elegant way to do this?
  1 件のコメント
G A
G A 2021 年 8 月 29 日
may be this way could be better:
function A = function1(n,S)
A = n + S.a + S.b + S.c + S.d;
end
function A = function2(n,S)
A = n*S.a*S.b;
end

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

採用された回答

Yongjian Feng
Yongjian Feng 2021 年 8 月 29 日
You don't need varargin
function A = function1(n,a,b, c, d)
A = n+a+b+c+d;
end
function A = function2(n,a,b, ~, ~)
A = n*a*b;
end
  7 件のコメント
Stephen23
Stephen23 2021 年 8 月 30 日
"what is the main difficulty to make (or reason not to make) it possible in the Editor to higlight structure name with its field throughout a function like it occurs with simple variables when you click on it or select it?"
You have to consider that variables in MATLAB are dynamically typed. In general it is difficult to determine the type of a variable until runtime (e.g. changes to function scoping, variables created dynamically, inputs are not typed, etc.)
G A
G A 2021 年 8 月 31 日
Thanks! - and I will accept this answer together with comments.

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

その他の回答 (1 件)

the cyclist
the cyclist 2021 年 8 月 29 日
I think the basic idea you need is
f1 = @(x) x;
f2 = @(x) x.^2;
f = @(a,x) (a~=0)*f1(x) + (a==0)*f2(x);
f(0,2)
ans = 4
f(1,2)
ans = 2
  4 件のコメント
G A
G A 2021 年 8 月 29 日
編集済み: G A 2021 年 8 月 29 日
Also, it is time consuming if two functions are executed instead of one. Better to put if-statement into a loop. I have half of answer to my question in my comment above: 0*inf = NaN, 0*A = 0, so to give the answer 0 or NaN, Matlab must execute f2 before multipliing its return by 0.
the cyclist
the cyclist 2021 年 8 月 29 日
Searching keywords such as conditional anonymous function MATLAB turns up a lot of these same ideas. I did not find a great solution.

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by