7
$\begingroup$

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
$\endgroup$
1

6 Answers 6

12
$\begingroup$
PadRight[Internal`PartitionRagged[v, Range@n]]

Mathematica graphics

$\endgroup$
3
  • $\begingroup$ 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? $\endgroup$
    – Rudinberry
    Sep 4, 2022 at 14:18
  • 1
    $\begingroup$ @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). $\endgroup$
    – Michael E2
    Sep 4, 2022 at 14:28
  • $\begingroup$ @Rudinberry it is better to include such extra details in your question. Can you, please, update your question with these details? $\endgroup$ Sep 4, 2022 at 17:39
9
$\begingroup$
  • 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
$\endgroup$
5
$\begingroup$

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

$\endgroup$
2
$\begingroup$

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

$\endgroup$
2
$\begingroup$
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}}

$\endgroup$
1
$\begingroup$

Using ReplacePart:

n = 5;
v = Range[n (n + 1)/2];
m = LowerTriangularize[ConstantArray[1, {n, n}]];
p = m // Position[1];
ReplacePart[m, Thread[p -> v]]

$\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)$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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