fzero implicit functions - how to make recursive function handles
조회 수: 3 (최근 30일)
이전 댓글 표시
I've been trying to implement a discrete ODE solver, but my iterations require an implicit function (f2), which also depends on the output of another function(f1)'s output with it's value as that function's input (i.e., f2(x) = ...f2(x). The function f1 will be an arbitrary handle which is the ODE.
Now, I do know that f2 will not be able to assign itself a handle, because f2 doesn't exist in the first place to refer to itself. But I do need this kind of a recursion because my implicit function demands it.
A simple version of the relevant part of the code is as follows, I've made f1 a sine, typically, it will be an input.
function x2 = fn(x)
f1 = @(x) sin(x);
f2 = @(x) x+f1(x)+f1(f2(x));
x2 = fzero(f2,x);
end
What would be the proper way to write line 3?
Thanks in advance.
댓글 수: 0
채택된 답변
Walter Roberson
2021년 6월 16일
You cannot. You are missing an essential part of recursion: there must always be a termination condition. Anonymous functions cannot themselves code tests that prevent recursive calls at the termination condition: you need a non-anonymous function.
댓글 수: 3
Walter Roberson
2021년 6월 16일
I am not sure that you do understand.
You do not proceed with your approach. You do not try to work around it by finding some way to make the handle visible to the function (which you can do if you use real functions), because your calculation would never end.
You want
f2(x) = x + f1(x) + f1(f2(x))
for a given x, this is
X = x
F1X = f1(x)
F2 == X + F1X + f1(F2)
X + F1X + f1(F2) - F2 == 0
so
obj = @(F2) X + F1X + f1(F2) - F2
F2 = fzero(obj, x0)
After that you have
x2 = fzero(f2,x);
so you want to solve for the x that makes F2 equal to 0. But if you know that F2 is equal to 0, then substitute that in:
f2(x) == x + f1(x) + f1(f2(x))
0 == x + f1(x) + f1(0)
magicx = fzero(@(x) x + f1(x) + f1(0), x0)
and this is independent of the x in
function x2 = fn(x)
unless different x for fn(x) correspond to different f1 functions, or unless different x for fn(x) correspond to different starting points for the fzero() search
... and f2 never needs to be calculated.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Configure Simulation Conditions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!