Skip to content

Instantly share code, notes, and snippets.

@ilkayisik
Last active February 19, 2021 10:40
Show Gist options
  • Save ilkayisik/089f6c1e740a93a75264284de8370a90 to your computer and use it in GitHub Desktop.
Save ilkayisik/089f6c1e740a93a75264284de8370a90 to your computer and use it in GitHub Desktop.
two ways of making a square matrix from a vector
'''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