Issue
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
Solution
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:
>>> N = 5
>>> vals = torch.arange(N*(N+1)/2) + 1
>>> A = torch.zeros(N, N)
>>> i, j = torch.triu_indices(N, N)
>>> A[i, j] = vals
>>> A.T[i, j] = vals
>>> vals
tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.,
15.])
>>> 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.]])
Answered By - swag2198
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.