H
H
HitGirl2022-04-03 10:41:31
Python
HitGirl, 2022-04-03 10:41:31

How to create a symmetric matrix from a list?

Hello!
I have an array of n elements: [1, 0.6, 0.8, 0.3]
Please tell me how to get such a matrix from it:
[
[1, 0.6, 0.8, 0.3],
[0.6, 1, 0.6, 0.8],
[ 0.8, 0.6, 1, 0.6],
[0.3, 0.8, 0.6, 1]
]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Leonid, 2022-04-03
@HitGirl

Just promise to understand how it turned out, okay?

l = [1, 0.6, 0.8, 0.3]
l_len = len(l)
res = [[l[abs(x-y)] for y in range(l_len)] for x in range(l_len)]
print(res) # [[1, 0.6, 0.8, 0.3], [0.6, 1, 0.6, 0.8], [0.8, 0.6, 1, 0.6], [0.3, 0.8, 0.6, 1]]

A
alexbprofit, 2022-04-03
@alexbprofit

import numpy as np

data = [1,0.6, 0.8, 0.3]

n = len(data)  # could be 24
 
x = np.array(data).reshape((1, n))
ind = np.zeros((n, n))
ind[x <= x.transpose()] = np.array(data + data + data[:2])
ind = ind + ind.transpose() - np.diag(np.diag(ind))
 
print(ind)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question