How to merge function handles in matlab?
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Stephen23
on 29 Jul 2015
Edited: Stephen23
on 29 Jul 2015
fun = @(a,b,n) arrayfun(@(nn)fk(a,b,nn), 1:n);
2 Comments
Guillaume
on 29 Jul 2015
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
More Answers (1)
Sean de Wolski
on 29 Jul 2015
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 Comments
Sean de Wolski
on 29 Jul 2015
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}
See Also
Categories
Find more on Multirate Signal Processing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!