Search code examples
pythonnumpy

How to merge an upper and lower triangular, also adding a diagonal of 1s


I have an upper and a lower diagonal triangular matrix, I want to merge these, but also add a diagonal of 1s.

Here is what I have...

upper = np.array([[0.90858992, 0.96590361, 0.95616282],
                 [       np.nan, 0.90055735, 0.8956839 ],
                 [       np.nan,        np.nan, 0.94590614]])

And the lower...

lower = np.array([[0.90858992,   np.nan,   np.nan    ],
                  [0.96590361, 0.90055735, np.nan    ],
                  [0.95616282, 0.8956839 , 0.94590614]])

This is what I want to produce:

np.array([
          [1, 0.90858992, 0.96590361,     0.95616282    ],
          [0.90858992,   1,     0.90055735,    0.8956839],
          [0.96590361, 0.90055735,        1, 0.94590614 ],
          [0.95616282, 0.8956839 , 0.94590614,    1     ]])

Does anybody have any suggestion as to how I can achieve this intended result? I have tried matrix addition, but can't seem to get it working


Solution

  • You can start from the identity matrix and then fill the upper/lower triangular parts.

    To access the upper/lower triangular parts of both input matrices and output matrix you can use np.triu_indices and np.tril_indices.

    The following code should create the expected out array.

    n = len(upper) + 1
    out = np.eye(n)
    out[np.triu_indices(n, 1)] = upper[np.triu_indices(n-1)]
    out[np.tril_indices(n, -1)] = lower[np.tril_indices(n-1)]