Last active
February 19, 2021 10:40
-
-
Save ilkayisik/089f6c1e740a93a75264284de8370a90 to your computer and use it in GitHub Desktop.
two ways of making a square matrix from a vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''make square matrix from vector''' | |
import numpy as np | |
nr_elems = 253 | |
vals = np.random.rand(nr_elems) | |
# first method using scipy distance: | |
from scipy.spatial import distance | |
vals_square_1 = distance.squareform(vals) | |
# second method using numpy | |
vals_square_2 = np.zeros([23, 23]) | |
vals_square_2[np.triu_indices(len(vals_square_2), k=1)] = vals | |
vals_square_2 = vals_square_2 + vals_square_2.T | |
np.all(vals_square_1 == vals_square_2) | |
as_matrix = spatial.distance.squareform(Y, force='tomatrix', checks=False) | |
# return upper part of a square matrix: | |
M[np.triu_indices(len(M), k=k)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment