How to fill a cell with function handles using iteration numbers?

9 ビュー (過去 30 日間)
ejk
ejk 2020 年 8 月 5 日
コメント済み: ejk 2020 年 8 月 5 日
I am trying to create N functions that are all extremely similar, except they use different constants from an N sized array.
I have a cell G = {}, but I'm not sure how to create a for loop that would set G{1} = @(x) c(1)*x (this is an example, not the actual function), where c is an array containing the constants cooresponding to each function.
I tried placing G{k} = @(x) c(k)*x and iterating k from 1 to N, but that creates functions that contain k, and not the actual iteration number 1, 2,...N.
  1 件のコメント
Ted Shultz
Ted Shultz 2020 年 8 月 5 日
you should check out cellfun, it can run functions on cells using cells as inputs.

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

採用された回答

Steven Lord
Steven Lord 2020 年 8 月 5 日
c = (1:10).^2;
G = cell(size(c));
for whichElement = 1:numel(c)
G{whichElement} = @(x) c(whichElement)*x;
end
Yes, when you display each element of G the expression that gets displayed will include whichElement. But the anonymous function remembers the value whichElement (and c for that matter) had when it was defined and will use those values when the anonymous function is evaluated.
G{7}(5) % 49*5 = 245

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by