7

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
Rudinberry
  • 315
  • 1
  • 5
  • 3
    Related: https://mathematica.stackexchange.com/questions/55659/populate-an-upper-triangular-matrix-from-a-vector-of-elements , and unfortunately, Statistics`Library`VectorToUpperTriangularMatrix doesn't have a sister function. Could use it + Transpose[]. – Michael E2 Sep 04 '22 at 13:57

4 Answers4

10
PadRight[Internal`PartitionRagged[v, Range@n]]

Mathematica graphics

Michael E2
  • 235,386
  • 17
  • 334
  • 747
  • 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? – Rudinberry Sep 04 '22 at 14:18
  • 1
    @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). – Michael E2 Sep 04 '22 at 14:28
  • @Rudinberry it is better to include such extra details in your question. Can you, please, update your question with these details? – CA Trevillian Sep 04 '22 at 17:39
7
  • When the data is a list.
n = 5;
v = Range[n (n + 1)/2];
TakeList[v, Range[n]] // PadRight
% // 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
cvgmt
  • 72,231
  • 4
  • 75
  • 133
4

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.

Borrowing from Mr.Wizard's answer here

MatrixForm@PadRight@partitionBy[v, # &]

mat

bmf
  • 15,157
  • 2
  • 26
  • 63
0

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]}]}]

enter image description here

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44