1

How to convert a non-symmetric numpy matrix to be a symmetric matrix?

the request is : if the element a[ i ][ j ] of upper triangle(above the diagonal) is 1, the element of lower triangle a[j][i] should be changed to 1.

The same for the lower triangle, if a[ i ][ j ] =1, the symmetric element a[ j ][ i ] in upper triangle should be 1.

Just care about change the element from 0 to 1,don;t change it from 0 to 1.

I can solve it with two or more for loops, but I want to know how to solve it in a more pythonic way with higher time efficiency?

Thanks in advance !

For example:

a= np.array ([[0, 0, 1, 0, 1],
              [0, 0, 0, 1, 1],
              [0, 0, 0, 1, 1],
              [1, 1, 0, 0, 0],
              [1, 1, 0, 1, 0]])

the result should be :

a= np.array ([[0, 0, 1, 1, 1],
              [0, 0, 0, 1, 1],
              [1, 0, 0, 1, 1],
              [1, 1, 1, 0, 1],
              [1, 1, 1, 1, 0]])
1
  • Did the posted solution work for you? If so, please consider accepting it. Commented Apr 29, 2020 at 15:12

1 Answer 1

1

One way purely with masking -

In [40]: m = a==1

In [41]: (m | m.T).view('i1')
Out[41]: 
array([[0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 0, 0, 1, 1],
       [1, 1, 1, 0, 1],
       [1, 1, 1, 1, 0]], dtype=int8)

Another with addition -

In [55]: ((a.T + a)>0).view('i1')
Out[55]: 
array([[0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 0, 0, 1, 1],
       [1, 1, 1, 0, 1],
       [1, 1, 1, 1, 0]], dtype=int8)

Another with just bitwise-OR-ing -

In [57]: (a.T | a)
Out[57]: 
array([[0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 0, 0, 1, 1],
       [1, 1, 1, 0, 1],
       [1, 1, 1, 1, 0]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, Divakar! I will try this!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.