views:

861

answers:

3

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).

A: 

You need a final condition for input x when myFunc stops calling Riemann. Also sending the actual function(in this case sin) to Riemann is a better idea than calling myFunc.

AnnaR
A: 

The function myfunc does not end after f = sin(1./x); where it should. Terminate the function there and call the plotting code from elsewhere (separate file).

From manual: You can terminate any function with an end statement but, in most cases, this is optional. end statements are required only in M-files that employ one or more nested functions. Within such an M-file, every function (including primary, nested, private, and subfunctions) must be terminated with an end statement. You can terminate any function type with end, but doing so is not required unless the M-file contains a nested function.

Muxecoid
+4  A: 

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)
PierreBdR
Thanks. That's the way to do it. Also just separating the for loop out of myfunc.m will solve the issue. Such a simple thing.
Matti