How to merge function handles in matlab?
2 ビュー (過去 30 日間)
古いコメントを表示
Hi!
I have a function handle of this form:
fk = @(a, b, k) a+b+k;
I would like to obtain another function handle that is actually a vector where every element is the first function handle evaluated in k, for k between 1 and a given n.
f = @(a, b) [fk(a, b, 1) fk(a, b, 2) ... fk(a, b, n)]
Example: for n =3, I would like to obtain
f = @(a,b) [fk(a, b, 1) fk(a, b, 2) fk(a, b, 3)]
How can I do this?
P.S.: I would like something that looks like a for loop, that can work for every given n.
0 件のコメント
採用された回答
Stephen23
2015 年 7 月 29 日
編集済み: Stephen23
2015 年 7 月 29 日
fun = @(a,b,n) arrayfun(@(nn)fk(a,b,nn), 1:n);
2 件のコメント
Guillaume
2015 年 7 月 29 日
Stephen's answer is just a more generic version of yours, and more importantly safer, if you're not aware of the closure behaviour of anonymous functions. Consider the result of
fk = @(a, b, k) a+b+k;
n = 2;
fun = @(a, b) arrayfun(@(k)fk(a,b,k),1:n); %your fun
fun(5, 6)
n = 5;
fun(5, 6) %for fun n is still 2
versus
fk = @(a, b, k) a+b+k;
fun = @(a, b, n) arrayfun(@(k)fk(a,b,k),1:n); %Stephen's fun
n = 2;
fun(5, 6, n)
n = 5;
fun(5, 6, n) %fun uses the new n
その他の回答 (1 件)
Sean de Wolski
2015 年 7 月 29 日
You can store those function handles in a cell using a for-loop or just run the for-loop over the k values.
for ii = 1:10
Cfun{ii} = @(a,b)f(a,b,ii);
end
2 件のコメント
Sean de Wolski
2015 年 7 月 29 日
They're actually equivalent, ii is a static copy of the integer that it is equal to at anonymous function creation, you can see its values by looking at the workspace values in functions:
q = 7
f = @(x)x*q
fv = functions(f)
fv.workspace{1}
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!