# Using RecurrenceTable index to call elements of a vector

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.

-
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}

-
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]];

-