Elegant way to get a symmetric Torch Tensor over diagonal
Is there an elegant way to build a Torch.Tensor like this from a given set of values?
Here is an 3x3 example, but in my application I would have a matrix of any odd-size.
A function call gen_matrix([a, b, c, d, e, f]) should generate


You can use torch.triu_indices() to achieve this. Note that for a general N x N symmetric matrix, there can be atmost N(N+1)/2 unique elements which are distributed over the matrix.
The vals tensor here stores the elements you want to build the symmetric matrix with. You can simply use your set of values in place of vals. Only constraint is, it should have N(N+1)/2 elements in it.
Short answer:
N = 5 # your choice goes here
vals = torch.arange(N*(N+1)/2) + 1 # values

A = torch.zeros(N, N)
i, j = torch.triu_indices(N, N)
A[i, j] = vals
A.T[i, j] = vals

Example:
&gt;&gt;&gt; N = 5
&gt;&gt;&gt; vals = torch.arange(N*(N+1)/2) + 1
 
&gt;&gt;&gt; A = torch.zeros(N, N)
&gt;&gt;&gt; i, j = torch.triu_indices(N, N)
&gt;&gt;&gt; A[i, j] = vals
&gt;&gt;&gt; A.T[i, j] = vals
  
&gt;&gt;&gt; vals
 tensor([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12., 13., 14.,
         15.])
&gt;&gt;&gt; A
 tensor([[ 1.,  2.,  3.,  4.,  5.],
         [ 2.,  6.,  7.,  8.,  9.],
         [ 3.,  7., 10., 11., 12.],
         [ 4.,  8., 11., 13., 14.],
         [ 5.,  9., 12., 14., 15.]])

