2
|
5465 Views
|
3 Replies
|
5 Total Likes
View groups...
Share
GROUPS:

# Recursive function help

Posted 11 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 with f and store that sum ?in location 1, then I need to take the new f and add it to f and ?store that sum in location 2. Hopefully this makes sense. Thanks,-Adriana
3 Replies
Sort By:
Posted 11 years ago
 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 likeFoldList[Plus, a, {b, c, d}]Out[] = {a, a + b, a + b + c, a + b + c + d}which gives the same asAccumulate[{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 11 years ago
 The function Accumulate should do the trick. In:= data = RangeOut= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}In:= Accumulate[data]Out= {1, 3, 6, 10, 15, 21, 28, 36, 45, 55}Paritosh
Posted 11 years ago
 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