2
$\begingroup$

How can I merge two trees, t and s, so as to form a square matrix below, where both trees starts from top-left (as shown), and occupy lower and upper triangular forms (in a transpose fashion). Trees can get larger. Diagonal contains zeros, but I will store some other information there later. Up to transpose, it doesn't matter which tree is on the bottom.

t = {{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}}
s = 10 t

output

{{0, 10, 10, 10, 10}, {1, 0, 20, 20, 20}, {1, 2, 0, 30, 30}, {1, 2, 3, 0, 40}, {1, 2, 3, 4, 0}}

or in matrix form:

enter image description here

$\endgroup$
1
  • 3
    $\begingroup$ ArrayPad[PadRight@t, {{1, 0}, {0, 1}}] and the same for s $\endgroup$
    – ybeltukov
    Nov 14, 2015 at 21:46

2 Answers 2

2
$\begingroup$
Transpose[#[[1]]] + #[[2]] &[PadRight[{s, t}, {2, -5, 5}]]
$\endgroup$
2
$\begingroup$
t = {{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}}
tm = Prepend[t, {}];
a = PadRight[#, 5] & /@ tm
a + 10 Transpose[a] // MatrixForm

UPDATE

Exploiting the much better and more concise advice in comment by ybeltukov:

b = ArrayPad[PadRight@t, {{1, 0}, {0, 1}}]
b + 10 Transpose[b] // MatrixForm
$\endgroup$
1
  • $\begingroup$ Both solutions are great. I wish I could select both. Thanks for the input. $\endgroup$ Nov 15, 2015 at 5:40

Your Answer

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

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