Fill upper triangular matrix from a list I am looking a good way to fill up the elements of a lower triangular matrix from a list.

I currently have this:

PadRight[#, s] &amp; /@ 
 Prepend[Take[elems, # + {1, 0}] &amp; /@ 
   Partition[Accumulate[Range[0, s - 1]], 2, 1], {}]


where elems is the elements-list and s is its length.

Perhaps the best way is preallocation plus a clear, procedural Do-loop.  What do you think?

You can test the above with:

s = 5
elems = Range[s(s-1)/2]
Here are a few methods for your consideration and feedback.



This one uses the core of my "Dynamic Partition" function.  It is the fastest method I know for this problem.  Also, perhaps refactoring the code like this makes it more intelligible.

dynP[l_, p_] := 
 MapThread[l[[# ;; #2]] &amp;, {{0}~Join~Most@# + 1, #} &amp;@Accumulate@p]

#~PadRight~s &amp; /@ {{}} ~Join~ dynP[elems, Range[s-1]]




This one is slightly shorter, using a different way to construct the indices, but also slightly slower, and perhaps less transparent.

#~PadRight~s &amp; /@ 
 Prepend[
   elems~Take~# &amp; /@ 
     Array[{1 + # (# - 1)/2, # (# + 1)/2} &amp;, s - 1],
   {}
 ]




This one is terse, but slow.  Legibility is debatable.

SparseArray[Join @@ Table[{i, j}, {i, s}, {j, i - 1}] -&gt; elems, s] // MatrixForm




Here is one I just came up with, and I am quite pleased with it.  I think it may be more understandable than most of the ones above.

Take[FoldList[RotateLeft, elems, Range[0, s - 1]] ~LowerTriangularize~ -1, All, s + 1]