How to recursively reduce the function arguments
조회 수: 4 (최근 30일)
이전 댓글 표시
Is there a way to create a function with one less argument dynamically? Basicly I'd like to find a way to do the following recursively or in a loop.
f4 = @(x1,x2,x3,x4) f5(x1, x2, x3, x4, 1);
f3 = @(x1,x2,x3) f4(x1, x2, x3, 1);
...
f1 = @(x1) f2(x1, 1);
r = f1(1)
function r = f5(x1, x2, x3, x4, x5)
r = x1 + x2 + x3 + x4 + x5
end
댓글 수: 2
David Hill
2021년 11월 9일
Very confusing. An example would be helpful. It seems to me that r=f1=f2=f3=f4=f5=4+x1; which equals 5 in the example above (x1=1). Not sure what you are trying to do, but it is not wise to have all those variables.
채택된 답변
Stephen23
2021년 11월 9일
It can be done with VARARGIN:
N = 5;
C = cell(1,N);
C{N} = @f5;
for k = N-1:-1:1
C{k} = @(varargin) C{k+1}(varargin{:},1);
end
C{1}(1)
function r = f5(x1, x2, x3, x4, x5)
r = x1 + x2 + x3 + x4 + x5;
end
추가 답변 (2개)
Jan
2021년 11월 9일
This should work with str2func and eval.
This is such a cruel programming technique, that I recommend not to use it. Such meta-programming for creating code dynamically is hard to debug and Matlab's JIT acceleration cannot work. This can slow down the code by a factor 100 compared to some code, which avoid the dynamic creation of variables and functions.
댓글 수: 1
Adam Danz
2021년 11월 9일
The function string could also be parsed to remove the penultimate input and then converted back to a function handle without using eval. But I still think there's a better approach.
Adam Danz
2021년 11월 9일
x1 = rand(1);
x2 = rand(1);
x3 = rand(1);
x4 = rand(1);
p = [x1, x2, x3, x4];
f5([p,1])
p = [x1, x2, x3];
f5([p,1])
p = [x1, x2];
f5([p,1])
function f5(varargin)
sum([varargin{:}])
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!