I need to make a matrix (in the form of a numpy array) by taking a list of parameters of length N and returning an array of dimensions N+1 x N+1 where the off-diagonals are symmetric and each triangle is made up of the values given. The diagonals are equal to 0 - the row sum of the off-diagonals.
I don't really like having to instantiate an empty array, fill the top triangle, then create a new matrix with the bottom triangle filled in. I'm wondering if I can do this in fewer lines (while still being readable) and also wondering if it can be made faster. vals
is never going to be very large (between 2 and 100, most likely) but the operation is going to be repeated many times.
def make_sym_matrix(dim, vals):
my_matrix = np.zeros([dim,dim], dtype=np.double)
my_matrix[np.triu_indices(dim, k=1)] = vals
my_matrix = my_matrix + my_matrix.T
my_matrix[np.diag_indices(dim)] = 0-np.sum(my_matrix, 0)
return my_matrix
dim
, try to reusexy=np.triu_indices(dim,1)
. Fordim=4
, that takes about half the time; so reuse may double the overall speed. \$\endgroup\$