フィルターのクリア

How to merge function handles in matlab?

5 ビュー (過去 30 日間)
Dina Irofti
Dina Irofti 2015 年 7 月 29 日
コメント済み: Sean de Wolski 2015 年 7 月 29 日
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.

採用された回答

Stephen23
Stephen23 2015 年 7 月 29 日
編集済み: Stephen23 2015 年 7 月 29 日
You could use arrayfun for this:
fun = @(a,b,n) arrayfun(@(nn)fk(a,b,nn), 1:n);
  2 件のコメント
Dina Irofti
Dina Irofti 2015 年 7 月 29 日
Actually this is what I was looking for
fun = @(a, b) arrayfun(@(k)fk(a,b,k),1:n);
Thank you for your answer. It was very useful!!
Guillaume
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
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 件のコメント
Dina Irofti
Dina Irofti 2015 年 7 月 29 日
Try this out
fk = @(a, b, k) a+b+k;
for ii = 1:10
Cfun{ii} = @(a,b)f(a,b,ii);
end
disp(Cfun)
The output is
Cfun =
Columns 1 through 7
@(a,b)f(a,b,ii) @(a,b)f(a,b,ii) @(a,b)f(a,b,ii) @(a,b)f(a,b,ii) @(a,b)f(a,b,ii) @(a,b)f(a,b,ii) @(a,b)f(a,b,ii)
Columns 8 through 10
@(a,b)f(a,b,ii) @(a,b)f(a,b,ii) @(a,b)f(a,b,ii)
What I would like to obtain is
Cfun =
Columns 1 through 7
@(a,b)f(a,b,1) @(a,b)f(a,b,2) @(a,b)f(a,b,3) @(a,b)f(a,b,4) @(a,b)f(a,b,5) @(a,b)f(a,b,6) @(a,b)f(a,b,7)
Columns 8 through 10
@(a,b)f(a,b,8) @(a,b)f(a,b,9) @(a,b)f(a,b,10)
Sean de Wolski
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}

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

カテゴリ

Help Center および File ExchangeMultirate Signal Processing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by