edesz
edesz

Reputation: 12406

Python NumPy concatenate 2 triangular arrays above/below diagonal

I am trying to combine 2 triangular NumPy arrays into a new array in Python. Each triangular array is half filled with values, with zeros on the diagonal. I need to merge these 2 arrays into one new combined array with zeros on the diagonal.

Here is the array X

import numpy as np
X = np.random.rand(4,4)

[[ 0.06681579  0.25793063  0.86489791  0.78399056]
 [ 0.7335036   0.99703778  0.40017913  0.07912444]
 [ 0.43533884  0.51517525  0.28110527  0.10793738]
 [ 0.19212844  0.704657    0.94657795  0.89042305]]

I then extract the lower and a modified version of the upper diagonal values from the array:

u = np.triu(X+1,k=1)
l = np.tril(X,k=-1)
print u
[[ 0.          1.25793063  1.86489791  1.78399056]
 [ 0.          0.          1.40017913  1.07912444]
 [ 0.          0.          0.          1.10793738]
 [ 0.          0.          0.          0.        ]]

print l
[[ 0.          0.          0.          0.        ]
 [ 0.7335036   0.          0.          0.        ]
 [ 0.43533884  0.51517525  0.          0.        ]
 [ 0.19212844  0.704657    0.94657795  0.        ]]

Now, I need to combine these 2 arrays u and l together such that:

  1. the upper triangle (not including diagonal) is filled with u
  2. the lower triangle (not including diagonal) is filled with l
  3. the diagonal is still filled with zeros

Here is what I am looking for:

[[ 0.          1.25793063  1.86489791  1.78399056]
 [ 0.7335036   0.          1.40017913  1.07912444]
 [ 0.43533884  0.51517525  0.          1.10793738]
 [ 0.19212844  0.704657    0.94657795  0.        ]]

Is there a way to concatenate these 2 NumPy arrays to get this output?

Upvotes: 0

Views: 893

Answers (1)

user2357112
user2357112

Reputation: 280837

u+l

That should suffice for most cases. If you need to be careful about preserving signed zeros, you can do something more cumbersome:

result = u.copy()
l_indices = numpy.tril_indices_from(l)
result[l_indices] = l[l_indices]

Upvotes: 5

Related Questions