Home > Back-end >  How to generate values from a diagonal to fill matrix
How to generate values from a diagonal to fill matrix

Time:10-12

I have the following diagonal matrix

a = array([[1, 0, 0, 0],
           [0, 2, 0, 0],
           [0, 0, 3, 0],
           [0, 0, 0, 4]])

And the desired out come is the following

 array([[1, 3, 4, 5],
        [3, 2, 5, 6],
        [4, 5, 3, 7],
        [5, 6, 7, 4]])

Each element is the sum of the corresponding diagonals. Thanks a lot

CodePudding user response:

Try:

>>> np.diag(a)   np.diag(a)[:, None] - a
array([[1, 3, 4, 5],
       [3, 2, 5, 6],
       [4, 5, 3, 7],
       [5, 6, 7, 4]])

Addendum

  1. What if a is a DataFrame?

    Then: np.diag(a) np.diag(a)[:, None] - a is also a DataFrame (with same index and columns as a).

  2. What if a is a numpy array, but I want a DataFrame result?

    Then use: pd.DataFrame(...) instead.

CodePudding user response:

You can use:

# get diagonal
diag = np.diag(a)

# outer sum
out = diag diag[:,None]
# or
# out = np.outer(diag, diag)

# reset diagonal
np.fill_diagonal(out, diag)

print(out)

output:

[[1 3 4 5]
 [3 2 5 6]
 [4 5 3 7]
 [5 6 7 4]]
  • Related