transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format
Do you just want to form a symmetric array? You can skip the diagonal indices completely.
m=np.array(m)
inds = np.triu_indices_from(m,k=1)
m[(inds[1], inds[0])] = m[inds]
m
array([[11, 12, 13],
[12, 22, 23],
[13, 23, 33]])
Creating a symmetric array from a:
new = np.zeros((3,3))
vals = np.array([11, 12, 13, 22, 23, 33])
inds = np.triu_indices_from(new)
new[inds] = vals
new[(inds[1], inds[0])] = vals
new
array([[ 11., 12., 13.],
[ 12., 22., 23.],
[ 13., 23., 33.]])
The fastest and smartest way to put back a vector into a 2D symmetric array is to do this:
Case 1: No offset (k=0) i.e. upper triangle part includes the diagonal
import numpy as np
X = np.array([[1,2,3],[4,5,6],[7,8,9]])
#array([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]])
#get the upper triangular part of this matrix
v = X[np.triu_indices(X.shape[0], k = 0)]
print(v)
# [1 2 3 5 6 9]
# put it back into a 2D symmetric array
size_X = 3
X = np.zeros((size_X,size_X))
X[np.triu_indices(X.shape[0], k = 0)] = v
X = X + X.T - np.diag(np.diag(X))
#array([[1., 2., 3.],
# [2., 5., 6.],
# [3., 6., 9.]])
The above will work fine even if instead of numpy.array
you use numpy.matrix
.
Case 2: With offset (k=1) i.e. upper triangle part does NOT include the diagonal
import numpy as np
X = np.array([[1,2,3],[4,5,6],[7,8,9]])
#array([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]])
#get the upper triangular part of this matrix
v = X[np.triu_indices(X.shape[0], k = 1)] # offset
print(v)
# [2 3 6]
# put it back into a 2D symmetric array
size_X = 3
X = np.zeros((size_X,size_X))
X[np.triu_indices(X.shape[0], k = 1)] = v
X = X + X.T
#array([[0., 2., 3.],
# [2., 0., 6.],
# [3., 6., 0.]])
You can use Array Creation Routines such as numpy.triu, numpy.tril, and numpy.diag to create a symmetric matrix from a triangular. Here's a simple 3x3 example.
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
a_triu = np.triu(a, k=0)
array([[1, 2, 3],
[0, 5, 6],
[0, 0, 9]])
a_tril = np.tril(a, k=0)
array([[1, 0, 0],
[4, 5, 0],
[7, 8, 9]])
a_diag = np.diag(np.diag(a))
array([[1, 0, 0],
[0, 5, 0],
[0, 0, 9]])
Add the transpose and subtract the diagonal:
a_sym_triu = a_triu + a_triu.T - a_diag
array([[1, 2, 3],
[2, 5, 6],
[3, 6, 9]])
a_sym_tril = a_tril + a_tril.T - a_diag
array([[1, 4, 7],
[4, 5, 8],
[7, 8, 9]])