fzero implicit functions - how to make recursive function handles
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Atakan Botasun
le 16 Juin 2021
Commenté : Atakan Botasun
le 16 Juin 2021
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 commentaires
Réponse acceptée
Walter Roberson
le 16 Juin 2021
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 commentaires
Walter Roberson
le 16 Juin 2021
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Configure Simulation Conditions dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!