edited tags
kglr
• 353.8k
• 17
• 416
• 784
Szabolcs
• 229.7k
• 28
• 599
• 1230

What is the best way to populate an upper triangular (or alternatively: lower triangular or symmetric) matrix from a vector of elements?

This example input:

{1, 2, 3, 4, 5, 6}


should give

{{0, 1, 2, 3},
{0, 0, 4, 5},
{0, 0, 0, 6},
{0, 0, 0, 0}}


or alternatively

{{0, 1, 2, 3},
{1, 0, 4, 5},
{2, 4, 0, 6},
{3, 5, 6, 0}}


or even

{{0, 0, 0, 0},
{1, 0, 0, 0},
{2, 3, 0, 0},
{4, 5, 6, 0}}


This problem has many solutions of course. I'm looking for the best (criteria: most elegant/readable, shortest, fastest) ones.

The input has length $$\binom{n}{2} = \frac{n(n-1)}{2}$$. Consider $$n$$ known. Feel free to use any version 10 functionality.

Szabolcs
• 229.7k
• 28
• 599
• 1230

What is the best way to populate an upper triangular (or alternatively: lower triangular or symmetric) matrix from a vector of elements?

This example input:

{1, 2, 3, 4, 5, 6}


should give

{{0, 1, 2, 3},
{0, 0, 4, 5},
{0, 0, 0, 6},
{0, 0, 0, 0}}


or alternatively

{{0, 1, 2, 3},
{1, 0, 4, 5},
{2, 4, 0, 6},
{3, 5, 6, 0}}


This problem has many solutions of course. I'm looking for the best (criteria: most elegant/readable, shortest, fastest) ones.

The input has length $$\binom{n}{2} = \frac{n(n-1)}{2}$$. Consider $$n$$ known. Feel free to use any version 10 functionality.

Szabolcs
• 229.7k
• 28
• 599
• 1230