2
$\begingroup$

I have one list a of length (n+1):

a={a[0],a[1],...,a[n]}

I wish to build a list by applying a function f, a recursive non-linear function, that depends on the value of a at both indexes i and (i-1) and on the previous value of the "under construction" list. The first value of list b is defined as b0. Here is the list I would like to get:

b={b0,f(b0,a[0],a[1]),...,f(b[n-1],a[n-1],a[n]))}

The first and last element of list a won't change but I want to test several values of incrementation, therefore n (the length of vector a) will change.

I have tried using Table, Array, combining it with Module and I managed to call at least one specific value by its index from list a but I can't find a way to do the multiple manipulations as described above.

$\endgroup$
2
  • $\begingroup$ Are a[i] numbers? Does the function f return a number? Or the same type of object as a[i]? $\endgroup$ Apr 19, 2017 at 20:22
  • $\begingroup$ both a and f are functions (that will be numbers only specific values of parameters) $\endgroup$
    – Elsa
    Apr 19, 2017 at 22:22

2 Answers 2

3
$\begingroup$

Here is one way:

avec = Array[a, 4, 0];
bvec = ConstantArray[b[0], Length[avec - 1]];
Do[
 bvec[[i]] = f[bvec[[i - 1]], avec[[i - 1]], avec[[i]]]
, {i, 2, Length[avec]}
]
bvec

{b[0], f[b[0], a[0], a[1]], f[f[b[0], a[0], a[1]], a[1], a[2]], f[f[f[b[0], a[0], a[1]], a[1], a[2]], a[2], a[3]]}

Or more functional:

bvec2 = FoldList[f[#1, Sequence @@ #2] &, b[0], Partition[avec, 2, 1]];
bvec == bvec2

True

$\endgroup$
0
$\begingroup$

In:

Clear[a, b, f, g, bs]
g[i_] := f[b[i - 1], a[i - 1], a[i]]
bs[n_] := Range[n] // MapThread[g, {#}] & // Join[{b[0]}, #] &
bs[4]

Out:

{b[0], f[b[0], a[0], a[1]], f[b[1], a[1], a[2]], f[b[2], a[2], a[3]], 
 f[b[3], a[3], a[4]]}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.