How to merge function handles in matlab?

9 views (last 30 days)
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.

Accepted Answer

Stephen23
Stephen23 on 29 Jul 2015
Edited: Stephen23 on 29 Jul 2015
You could use arrayfun for this:
fun = @(a,b,n) arrayfun(@(nn)fk(a,b,nn), 1:n);
  2 Comments
Dina Irofti
Dina Irofti on 29 Jul 2015
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 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

Sign in to comment.

More Answers (1)

Sean de Wolski
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
Dina Irofti
Dina Irofti on 29 Jul 2015
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 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}

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!