Calling user functions recursively

조회 수: 3 (최근 30일)
Isabelle Armanville
Isabelle Armanville 2017년 2월 20일
편집: Stephen23 2017년 2월 20일
I have user created functions called f11(), f12(), f13(), f21(), f22(), f23()... I want to call these function recursively for i=1 to n for j=j to m eval(fij()) I have tried with the eval() function. It does not work. Could someone help me? thank you
  댓글 수: 1
John D'Errico
John D'Errico 2017년 2월 20일
And yet another reason not to write numbered functions, numbered variables, etc. Regardless, you are asking to call them in sequence, but not recursively. A recursive call is one where a function calls itself.

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

답변 (2개)

dbmn
dbmn 2017년 2월 20일
First of all: Listen to John - he is right about this. Try not to use numbered functions and variables (you can read why this is a bad idea on numerous posts on Matlab Answers - just search).
But because I know you gonna try it anyway, here is a solution
A) Do nothing but change your eval to: (BAD)
eval(sprintf('f%d%d()', i, j))
B) Create a function caller that handles your functions (Better, but uses still the numbered functions - but at least it can be debugged)
function [] = function_caller(idx)
switch idx
case 1
% your function here
case 2
% your function here
end
end
C) Rewrite your code and avoid the numbered functions - there must be a smarter way to do this.
Work with Functions and Subfunctions instead and try to get a clear image about what your code actually needs to do in what order.

Stephen23
Stephen23 2017년 2월 20일
편집: Stephen23 2017년 2월 20일
Why not just put the functions into a cell array, then this is trivial:
>> C = {@rand,@()randi(9,1),@()randi([10,20],1)};
>> cellfun(@(f)f(),C)
ans =
0.91338 6 11
or
for k = 1:numel(C)
C{k}()
end
Calling numbered functions is not a good solution:

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by