# Saving variables from nested function

There has to be a simple solution for my question:

I have three functions and each uses the output from the previous function as its input:

x=1;
fx1 = 1 + x;
fx2 = %^2;
fx3 = %-2;


If I want three iterations of the code above

Nest[((1 + #)^2) - 2 &, 1, 3]


works and the result is as expected (62). However, my code is much longer and confusing than this example, so I had to assign names to the functions. If I try to do:

Nest[fx3@fx2@fx1[{x}] &, 1, 3]


it no longer works. I might simply not be using the Nest or other functions properly. Additionally, my first function contains a RandomVariate on it that doesn't seem to work either once it is nested. For example, my code could look like:

x=1;
fx1 = RandomVariate[NormalDistribution[]] + x;
fx2 = %^2;
fx3 = %-2;


I would like to generate n loops referencing the functions by their names, where RandomVariate produces a new value with each loop, and the value of x at the end is used as the initial value of x for the next loop. Ive tried, but I am much too new at this still. Any help is greatly appreciated!

There are several things that I think you misunderstand. The most important recommendation would be to use this question as a trigger to go to the help and read up on the functions involved and on related tutorials

First, a working solution to ease your mind

fx1[x_] := 1 + x + RandomVariate[NormalDistribution[]];
fx2[x_] := x^2;
fx3[x_] := x - 2;

Nest[Composition[fx1, fx2, fx3], 1, 3]


When you do this

x=1;
fx1 = 1 + x;
fx2 = %^2;
fx3 = %-2;


The % symbol refers to the output of the previous bunch of code sent to the kernel to evaluate. In this case, the previous line. If you look at the values returned by evaluating fx1 and the others, you will see that they actually store values, (1, 2, 4, 2 for x, fx1, fx2, fx3). They are no functions. In other words, doing fx1[9] will just give 2[9]

• Indeed, I am sure I still misunderstand several other basic things as well, but thank you for clarifying and pointing me in the right direction! Commented Nov 25, 2012 at 13:04

You can use # and & which you are apparently already familiar with:

fx1 = 1 + # &;
fx2 = #^2 &;
fx3 = #-2 &;

Nest[fx3@fx2@fx1@# &, x, 3]


62

• Thank you Mr. Wizard! That was what I was trying to do. Commented Nov 25, 2012 at 13:23