Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am trying to compute a sequence of functions using iteration and keep running into problems trying to use built in looping commands because of the recursive nature of the definition. The code below (version 8) shows the first two functions y1 and y2. The output functions are also piecewise linear. Is there an easier way to compute yn for any $n$?

{a1, b1} = {.3, .6}; {a2, b2} = {.6, .3};

y0[x_] := x;

f1[x_] := b1*y0[x/a1];

g1[x_] := (b2 - b1)*y0[(x - a1)/(a2 - a1)] + b1;

h1[x_] := (1 - b2)*y0[(x - a2)/(1 - a2)] + b2;

y1[x_] := If[0 <= x < a1, f1[x], If[a1 <= x < a2, g1[x], h1[x]]];

Plot[y1[x], {x, 0, 1}]

f2[x_] := b1*y1[x/a1];

g2[x_] := (b2 - b1)*y1[(x - a1)/(a2 - a1)] + b1;

h2[x_] := (1 - b2)*y1[(x - a2)/(1 - a2)] + b2;

y2[x_] := If[0 <= x < a1, f2[x], If[a1 <= x < a2, g2[x], h2[x]]];

Plot[y2[x], {x, 0, 1}]
share|improve this question

1 Answer 1

up vote 4 down vote accepted

You don't need to loop, you can just do the recursion directly:

Clear[y, f, g, h];
y[0, x_] := x;
y[n_, x_] /; 0 <= x < a1 := f[n, x];
y[n_, x_] /; a1 <= x <= a2 := g[n, x];
y[n_, x_] := h[n, x];
f[n_, x_] := b1 y[n - 1, x/a1];
g[n_, x_] := (b2 - b1) y[n - 1, (x - a1)/(a2 - a1)] + b1;
h[n_, x_] := (1 - b2) y[n - 1, (x - a2)/(1 - a2)] + b2;

The main trick is to pass in n as one of the parameters to the functions. When you are doing recursion, always remember the termination condition! I've split the y function into several definitions with different conditions (/;). You could keep it as one big If statement if that's more comfortable.

Plot[y[7, x], {x, 0, 1}]

y7

share|improve this answer
    
Thanks, works perfectly! –  Jon Dec 9 '13 at 21:43
    
This seems to be a good case to use memoization. –  shrx Dec 10 '13 at 0:15
    
Actually I'm not sure how one would effectively memoise this. How do you cope with the conditions on the argument that isn't memoised? –  wxffles Dec 10 '13 at 1:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.