How to store functions in a array

28 ビュー (過去 30 日間)
Bradley Kitzul
Bradley Kitzul 2020 年 12 月 9 日
コメント済み: Bradley Kitzul 2020 年 12 月 10 日
Below is a simple example of the code I am trying to implement (using it as proof of concept). I am trying to make an array (d) with 5 functions/equations and incrementing with i and at each slot of i. When I run the code the "i" in the x/i term is not incrementing with the for loop. I am trying to have the output of this code an array and each term in the array = [x/1, x/2, x/3, x/4, x/5].
for i=1:5
d{i} = @(x) x/i
end
  1 件のコメント
Bradley Kitzul
Bradley Kitzul 2020 年 12 月 10 日
Thank you!

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

回答 (2 件)

Steven Lord
Steven Lord 2020 年 12 月 9 日
The anonymous functions do "remember" the value the variable i had when they were created, even if they don't show it. If you want to see this use the functions function (but I strongly recommend against using functions as part of your production code. Just use it for debugging.)
for k = 1:5 % I tend not to use i as a variable, as it already means sqrt(-1) in MATLAB
d{k} = @(x) x./k;
end
d{4}
ans = function_handle with value:
@(x)x./k
y = d{4}([8 12]) % results in [2 3]
y = 1×2
2 3
f = functions(d{4});
f.workspace{1}
ans = struct with fields:
k: 4
  1 件のコメント
Bradley Kitzul
Bradley Kitzul 2020 年 12 月 10 日
Thank you!

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


Walter Roberson
Walter Roberson 2020 年 12 月 9 日
for i=1:5
d{i} = @(x) x/i;
end
d
d = 1x5 cell array
{@(x)x/i} {@(x)x/i} {@(x)x/i} {@(x)x/i} {@(x)x/i}
d{3}(7)
ans = 2.3333
It might not display the way you hoped, but it does work.
If it is important to it displays the way you want, you are going to have to construct it from strings.
for i=1:5
d{i} = str2func("@(x) x/" + i);
end
d
d = 1x5 cell array
{@(x)x/1} {@(x)x/2} {@(x)x/3} {@(x)x/4} {@(x)x/5}
d{3}(7)
ans = 2.3333
  1 件のコメント
Bradley Kitzul
Bradley Kitzul 2020 年 12 月 10 日
Thank you!

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

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by