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. Symmetric arrays are useful in linear algebra, network analysis, and graph theory. NumPy offers various methods to create a 2D symmetric array, which are as follows:
1. Using “np.triu()” and “np.tril()”:
Here, we first import the NumPy library and assign it the alias np
. The symmetric_array
function takes a NumPy array arr
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. It then uses np.tril()
to extract the lower triangular part of the transposed array (excluding the diagonal) by passing the transpose of the input array arr.T
and a value of -1
for k
, which means that the diagonal elements are excluded. Finally, 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]
. The code includes an example usage of the function.
2. Using “np.triu_indices()” and “np.tril_indices()”:
Here, we first import the NumPy library and assign it the alias np
. The symmetric_array
function takes a square NumPy array arr
as input and returns a new array sym_arr
that is symmetric along its diagonal, creating an empty array sym_arr
with the same shape as the input array. It then uses np.triu_indices()
to get the indices of the upper triangular part of the array, and sets those values in the sym_arr
using the np.ndarray.__setitem__()
method. Next, it uses np.tril_indices()
to get the indices of the lower triangular part of the transposed array (i.e., the diagonal values are excluded), and sets those values in the sym_arr
using np.ndarray.__setitem__()
method. Finally, it returns the resulting symmetric array sym_arr
. The code includes an example usage of the function.