필터 지우기
필터 지우기

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 CenterFile Exchange에서 Multirate Signal Processing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by