Message Boards Message Boards

2
|
6023 Views
|
3 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Recursive function help

Posted 12 years ago
Hi everyone. I'm able to create a basic recursive function, but ?I need to apply a recursive function to a list of numbers, that gives me a ?list of numbers back. Let me explain. I have a list of numbers. I need to add f[1] with f[0] and store that sum ?in location 1, then I need to take the new f[1] and add it to f[2] and ?store that sum in location 2. Hopefully this makes sense. Thanks,

-Adriana
POSTED BY: Adriana O'Brien
3 Replies
I would like to add some info to these nice answers. If you deal with addition, then Paritosh answer is the simplest solution. Yet if your recursive function is more elaborate then addition, then you will probably need what Seth recommended. Documentation gives basic example how FoldList works with function f (note that the f itself is not recursive, - the recursion is provided by FoldList):
FoldList[f, x, {a, b, c, d}]
Out[] = {x, f[x, a], f[f[x, a], b], f[f[f[x, a], b], c], f[f[f[f[x, a], b], c], d]}
So the same idea applied to your case would look like
FoldList[Plus, a, {b, c, d}]
Out[] = {a, a + b, a + b + c, a + b + c + d}
which gives the same as
Accumulate[{a, b, c, d}]
{a, a + b, a + b + c, a + b + c + d}
And in a case of a function more complex than addition you need something like:
FoldList[#1^#2 &, x, {a, b, c, d}]
Out[] = {x, x^a, (x^a)^b, ((x^a)^b)^c, (((x^a)^b)^c)^d}
POSTED BY: Vitaliy Kaurov
The function Accumulate should do the trick.
In[6]:= data = Range[10]
Out[6]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
In[7]:= Accumulate[data]
Out[7]= {1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
Paritosh 
POSTED BY: Paritosh Mokhasi
Perhaps you could flesh out your question a bit more, but I am wondering if the FoldList command might help you:

http://reference.wolfram.com/mathematica/ref/FoldList.html
POSTED BY: Seth Chandler
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract