I am trying to improve some pieces of coding I use frequently and am stuck with the following. I suspect there is a very similar answer but was unable to find it.
Function fun
with 3 arguments "walks" over three lists of equal length (contained in sp
). The 4th argument a
is the value of the function in the last step. Essentially, I want to MapThread at position I across the length of the lists while also using the last evaluation. I tried to use Fold
or Nest
together with Reap/Sow
but to no avail. The output is the evaluation of the function, and a working example with a Do
loop is as follows.
sp = RandomInteger[{1, 10}, {3, 10}]
fun[{x_, y_, z_, a_}] := 2 x - y + 3 z - 2 a
atposI = 0; lastval := 0; output := {};
Do[{
atposI = Append[sp[[All, i]], lastval];
lastval = fun[atposI];
output = Append[output, lastval]
}, {i, 1, 10}]
output
Input:
{{7, 1, 5, 10, 10, 2, 5, 10, 10, 6}, {4, 1, 4, 2, 5, 2, 2, 4, 8, 10}, {2, 6, 1, 4, 6, 7, 4, 1, 2, 8}}
Result
{16, -13, 35, -40, 113, -203, 426, -833, 1684, -3342}
I am particularly interested in solutions that contain Fold, Nest and Reap/Sow, although any answer is more than welcome.
FoldPairList
does this, or similar enough, if I understand your question right. $\endgroup$