Using different functions in a loop

Dear all,
I need to generate different indicators based on the same data but from a set of functions in a loop. Is there a way to specify different functions in a for loop?
Thanks.
Joe

1 件のコメント

Peng Zhou
Peng Zhou 2021 年 5 月 28 日
I seem to find a clumsy way myself involving eval:
for ii = 1:length(function_cell{ii})
hhh = eval(['@', function_cell{ii}]); % define a function handle for the ii-th function
zzz = hhh(inputs);
end
If there is any better approach, please let me know. Thanks.

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

 採用された回答

Stephen23
Stephen23 2021 年 5 月 28 日
編集済み: Stephen23 2021 年 5 月 28 日

0 投票

Convert strings-of-function-names to function handles (which they should be anyway):
C = {'sin','sqrt','abs'};
C = cellfun(@str2func,C,'uni',0); % convert
for k = 1:numel(C)
C{k}(-1) % call
end
ans = -0.8415
ans = 0.0000 + 1.0000i
ans = 1

その他の回答 (1 件)

Jan
Jan 2021 年 5 月 28 日

0 投票

for ii = 1:length(function_cell)
zzz = feval(function_cell{ii}, inputs);
end

1 件のコメント

Peng Zhou
Peng Zhou 2021 年 5 月 28 日
Thank you! I should have known feval.

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2021a

タグ

質問済み:

2021 年 5 月 28 日

コメント済み:

2021 年 5 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by