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

I am having trouble doing something that seems straightforward. I have a recursive sequence that I would like to produce which looks as follows:

a2 = {1, 2, 3}
RecurrenceTable[{a1[n + 1] == a1[n] + a2[[n]], a1[1] == 1}, a1, {n, 1, 3}]

This seems like it should work, but Mathematica is complaining about n not being an integer when I try to call the $n$-th part of a2. What I am really interested in is a very large RecurrenceTable of this form rather than what I have posted. Since RecurrenceTable seems to be much more efficient at generating large recursive sequences than any other functions I have been able to find, I would love to find a way to be able to use it.

share|improve this question
Do you mean to have both a and a1? – Jonathan Shock Jun 5 '13 at 15:52

Maybe something like this:

a2List = {1, 2, 3};
a2[n_Integer] := a2List[[n]];

RecurrenceTable[{a1[n + 1] == a1[n] + a2[n], a1[1] == 1}, a1, {n, 1, 4}]
   {1, 2, 4, 7}

OTOH, for this particular case, Fold[] is more expedient:

FoldList[Plus, 1, {1, 2, 3}]
   {1, 2, 4, 7}
share|improve this answer
For this particular case: Accumulate[a2] + 1 – bill s Jun 5 '13 at 17:06
Indeed, Accumulate[] is even better. (Sadly, I still haven't shaken off the habit of remembering Accumulate[] as the old name for Fold[]...) – J. M. Jun 5 '13 at 17:14

While Fold or Accumulate are probably better solutions for this specific problem, depending on your larger problem you might also want to consider a recursive approach, which can be written in a similar form to your original problem statement.

b = {1, 2, 4, 3, 2};
a[n_] := a[n - 1] + b[[n]];
a[0] := 0;

With these definitions, you can calculate the values of a using

a /@ Range[Length[b]]

which gives {1, 3, 7, 10, 12} as expected.

For larger problems you might also want to "memoize" this, which is a technique for storing past values of the function instead of recalculating them on-the-fly. For this, you would use

    a[n_] := a[n] = a[n - 1] + b[[n]];
share|improve this answer

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.