6
$\begingroup$

Let's say I have a list of values, for example {3,7,8,10}. Now I want to make a function that creates a table T in the following way:

$\begin{matrix} 3&7&8&10\\ &10&15&18\\ &&25&33\\ &&&58\\ \end{matrix}$

So we're adding up: 3+7=10, 7+8=15 etc.

Another complicating factor is that I want T[[2,2]]=10 (not T[[2,1]]); similarly, T[[4,4]]=58 etc.

BACKGROUND: In the end I am trying to make a function for Romberg Integration.

$\endgroup$
7
$\begingroup$
lst = {3, 7, 8, 10};

nl = NestList[MovingMap[Total, #, 1]&, lst, Length[lst] - 1]

{{3,7,8,10},{10,15,18},{25,33},{58}}

TeXForm @ MatrixForm @ PadLeft[nl, Automatic, ""]

$\left( \begin{array}{cccc} 3 & 7 & 8 & 10 \\ \text{} & 10 & 15 & 18 \\ \text{} & \text{} & 25 & 33 \\ \text{} & \text{} & \text{} & 58 \\ \end{array} \right)$

Alternatively, you can also use

Total /@ Partition[#, 2, 1] & (* or *)

Partition[#, 2, 1, {1, -1}, {}, Plus] &

in place of MovingMap[Total, #, 1]& above.

To get a 4X4 matrix, you can use PadLeft (with default padding 0):

nl2 = PadLeft[nl]

{{3, 7, 8, 10}, {0, 10, 15, 18}, {0, 0, 25, 33}, {0, 0, 0, 58}}

nl2[[4, 4]]

58

TeXForm @ MatrixForm @ nl2

$\left( \begin{array}{cccc} 3 & 7 & 8 & 10 \\ 0 & 10 & 15 & 18 \\ 0 & 0 & 25 & 33 \\ 0 & 0 & 0 & 58 \\ \end{array} \right)$

$\endgroup$
  • $\begingroup$ Thanks! That solves the first problem, but not the second: nl[[4,1]] is now 58 while it should be nl[[4,4]] $\endgroup$ – GambitSquared Oct 10 '19 at 14:41
  • $\begingroup$ @GambitSquared, please see the updated version. In general, you can use your choice of padding in the third argument in nl2= PadLeft[nl, Automatic, padding] to fill the lower triangular part ( j < i) of nl2. $\endgroup$ – kglr Oct 10 '19 at 14:51
  • $\begingroup$ Great! One more question: can I also (instead of Total) do some function on the two values? f[#1,#2] $\endgroup$ – GambitSquared Oct 10 '19 at 15:15
  • $\begingroup$ @GambitSquared, does NestList[f @@@ Partition[#, 2, 1] &, lst, 3] give the desired result? $\endgroup$ – kglr Oct 10 '19 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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