How to call functions indirectly?

Hi,
I would like to know how to call functions indirectly. For example: lets supose I have a data vector X, the functions F1.m, F2.m and F3.m (which input is the variable X) and I put these functions names in a list:
X=rand(1,100);
Myfuns={'F1','F2','F3'};
What I do today is something like:
Y(1)=F1(X);
Y(2)=F2(X);
Y(3)=F3(X);
What I would like to do is to call these functions using the variable Myfuns. Something like
for i=1:length(Myfuns)
Y(i)=Myfuns{i}(X);
end
Of course this doesn't work, but is there a way to do something this?
Thank you,
Bernard.

 채택된 답변

Daniel Shub
Daniel Shub 2012년 5월 25일

1 개 추천

You can do it with only additions to your code
F1 = @(a)length(a);
F2 = @(b)sum(b);
F3 = @(c)min(c);
X=rand(1,100);
Myfuns={'F1','F2','F3'};
for ii = 1:length(Myfuns)
eval(['Myfuns{ii} = @(x)', Myfuns{ii}, '(x)']);
end
for i=1:length(Myfuns)
Y(i)=Myfuns{i}(X);
end
If the functions are contained in files that exist on the path, then you can use str2fcn instead of eval
Myfuns = cellfun(@str2func, Myfuns, 'UniformOutput', false);
The best is to define the function handles directly:
Myfuns={@(x)F1(x),@(x)F2(x),@(x)F3(x)};

댓글 수: 4

Titus Edelhofer
Titus Edelhofer 2012년 5월 25일
Hi,
that's right. Just a side note: if your function has only one input, there is no need to add overhead using an anonymous function, e.g.
F1 = @length;
Myfuns = {F1, F2, F3};
Titus
Daniel Shub
Daniel Shub 2012년 5월 25일
That is a good point. I always add the input. I have never timed it to see if it matter. I would hope the JIT would deal with it.
Bernard Küsel
Bernard Küsel 2012년 5월 25일
Thanks for the answers!
What changes if my functions have more than one input?
For example:
Y=F1(x,y,z)
Daniel Shub
Daniel Shub 2012년 5월 25일
Thanks is an upvote and/or an accepted answer. If you read up on function handles, I think it will be obvious what to change.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by