What is the concept of a 2D Symmetric Array Subclass in Python?

Hey, I am Seeking clarification on the creation of a 2D Symmetric Array Subclass in Python using NumPy. Could someone provide a concise explanation and illustrate the concept with a code snippet?

1 Like

Hello @safiaa.02, a symmetric array has the same values across its diagonal axis, meaning the value at the i-th row and j-th column is equal to the value at the j-th row and i-th column. These arrays are useful in linear algebra, network analysis, and graph theory. Here is how you can implement this in code:

  • In this code, a custom function is created that takes a NumPy array as input and returns a new array that is symmetric along its diagonal.
  • It uses np.triu() to extract the upper triangular part of the input array. and np.tril() to extract the lower triangular part of the transposed array and k=1 is specified which means that the diagonal elements are excluded.
  • Lastly, the function adds the upper and lower triangular parts together to create a symmetric array. The resulting array has the same shape as the input array, and each element Z[i,j] is equal to Z[j,i].

I hope this will be helpful to you.

You can this method for a better understanding of the concept. Below is an example code present that utilizes NumPy to define a function, symmetric_array, which transforms a square input array into a symmetric matrix by populating its upper triangular part with the original values and the lower triangular part with values from the transpose of the array. The process involves creating an empty symmetric array, determining indices for the upper and lower triangles using NumPy functions, and updating the symmetric array accordingly. The resulting symmetric matrix is returned.