Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

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:

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!

share|improve this question

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

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]

share|improve this answer
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! – Pancholp Nov 25 '12 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]


share|improve this answer
Thank you Mr. Wizard! That was what I was trying to do. – Pancholp Nov 25 '12 at 13:23

Your Answer


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.