# How to fill lower trianglar matrix with elements of a vector

Given a dimension $$n$$ and a vector $$v$$ such as

n = 5
v = Range[n (n + 1)/2]


Is there any way to automate the construction of the following lower triangular matrix $$X$$, given arbitrary $$n$$ and $$v$$?

X = {{1, 0, 0, 0, 0}, {2, 3, 0, 0, 0}, {4, 5, 6, 0, 0}, {7, 8, 9, 10,
0}, {11, 12, 13, 14, 15}} // MatrixForm

• Related: mathematica.stackexchange.com/questions/55659/… , and unfortunately, StatisticsLibraryVectorToUpperTriangularMatrix doesn't have a sister function. Could use it + Transpose[]. Sep 4, 2022 at 13:57

PadRight[InternalPartitionRagged[v, Range@n]]


• Thank you! What if the elements of $v$ are of the form {v[1] -> 1, v[2]->2,...}. How can I extract the numerical values without the name v[1] and add them to the lower triangular matrix as you showed? Sep 4, 2022 at 14:18
• @Rudinberry If the values are in order, then Values[list]. Otherwise Array[v, m] /. list, where m is how many v[k] you have (or Array[v, Length[list]] if the length varies). Sep 4, 2022 at 14:28
• @Rudinberry it is better to include such extra details in your question. Can you, please, update your question with these details? Sep 4, 2022 at 17:39
• When the data is a list.
n = 5;
v = Range[n (n + 1)/2];
% // MatrixForm

• When the data is the Rule
n = 5;
rules = Table[v[i] -> i, {i, 1, Total@Range@n}]
Values /@ TakeList[rules, Range@n] // PadRight


Though there are already excellent answers by Michael and cvgmt, we still have a long way to go to ten ways of achieving the result.

MatrixForm@PadRight@partitionBy[v, # &]


Just another way to do it:

MapThread[Composition[PadRight[#, n] &, Plus[#1, #2] &], {Map[Array[# &, #] &, Range[n]], MapThread[ConstantArray[#1, #2] &, {Map[1/2 (# - 1) # &, Range[n]], Range[n]}]}]


n = 5;

v = Range[n (n + 1)/2];


Using FoldPairList and TakeDrop

PadRight @ FoldPairList[TakeDrop, v, Range @ n]


{{1, 0, 0, 0, 0},
{2, 3, 0, 0, 0},
{4, 5, 6, 0, 0},
{7, 8, 9, 10, 0},
{11, 12, 13, 14, 15}}

Using ReplacePart:

n = 5;
v = Range[n (n + 1)/2];
m = LowerTriangularize[ConstantArray[1, {n, n}]];
p = m // Position[1];
`
$$\left( \begin{array}{ccccc} 1 & 0 & 0 & 0 & 0 \\ 2 & 3 & 0 & 0 & 0 \\ 4 & 5 & 6 & 0 & 0 \\ 7 & 8 & 9 & 10 & 0 \\ 11 & 12 & 13 & 14 & 15 \\ \end{array} \right)$$