Search code examples
pythonmatlabnumpymatrix

Making a numpy ndarray matrix symmetric


I have a 70x70 numpy ndarray, which is mainly diagonal. The only off-diagonal values are the below the diagonal. I would like to make the matrix symmetric.

As a newcomer from Matlab world, I can't get it working without for loops. In MATLAB it was easy:

W = max(A,A')

where A' is matrix transposition and the max() function takes care to make the W matrix which will be symmetric.

Is there an elegant way to do so in Python as well?

EXAMPLE The sample A matrix is:

1 0 0 0
0 2 0 0
1 0 2 0
0 1 0 3

The desired output matrix W is:

1 0 1 0
0 2 0 1
1 0 2 0
0 1 0 3

Solution

  • Found a following solution which works for me:

    import numpy as np
    W = np.maximum( A, A.transpose() )