Search code examples
matlabrecursionfunction-handle

MatLab recursion error (beginner)


Ok. So i've got two function in MatLab that are calling each other.

Riemann.m

function I = Riemann(f, dx, a, b)
   x = a:dx:b;
   fx = f(x).*dx;
   I = sum(fx);

and myfunc.m

function f = myfunc(x)
   f = sin(1./x);
   for n=1:100
        I = Riemann(@myfunc, 0.001, 1/n, 1);
   end
   plot(I)

The problem is getting that to run. How do I call myfunc to get anything out of that. Everything I've tried ends up in an endless recursive call stack (which makes sense).


Solution

  • Your problem is with the definition of your functions: to be able to work with recursive definition, you must be able to compute at least one of the two function without the other, at least for some values. You must also make sure that every computation will end up relying on these result you can obtain without recursion.

    For your specific problem, I have the feeling you want to integrate the function f(x)=sin(1./x). If so, the code of your second function should read:

    function f = myfunc(x)
       fct = @(x) sin(1./x);
       f = fct(x);
       for n=1:100
            I = Riemann(fct, 0.001, 1/n, 1);
       end
       plot(I)