MATLAB Answers

fzero implicit functions - how to make recursive function handles

6 views (last 30 days)
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);
What would be the proper way to write line 3?
Thanks in advance.

Accepted Answer

Walter Roberson
Walter Roberson on 16 Jun 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.
Atakan Botasun
Atakan Botasun on 16 Jun 2021
So, looking at your response, I've figured out that I've done a small mistake in defining f2, as in f2 == 0 is a condition, so f2 itself must be subtracted from my expression. The solution was not in messing with handles thanks to your explanation, but parametrizing one that has two variables, as I already know one of the points. For the other point, I've made fzero start guessing from the previous point after parametrization.
Here's the new version (that has considerably more information about the problem itself), I'm still working on it to understand if it is adequate, but there are no major errors:
function [k1, k2, x2] = fn2(x1)
f = @(x) -x^2*cos(x)*sin(x);
f2 = @(y,x) x+.5*(f(x)+f(y))-y;
fun = @(y)f2(y,x1);
x2 = fzero(fun,x1);
k1 = f(x1);
k2 = f(x2);
So this time I didn't forget to subtract the next iterate (renamed as y this time) from itself to get the handle f2 to represent something that is supposed to be zero. Parametrizing with the known value for x which is x1, I've obtained x2 using fzero, the only caveat I'm worried about being the initial guess. I've compared my results with the Runge-Kutta 4 solver to feel safer, doesn't look half bad.
So, thanks for making the inner workings of fzero a bit clearer to me.

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!