Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an upper triangular matrix

Tags:

python

matrix

I need create upper triangular matrix given a set of values(the order is not importation). The matrix could be too large to input manually. np.triu only gives you the upper triangular of a existing matrix, not creating a new one.

I am doing some optimization to get the parameters of upper triangular cholesky root of covariance matrix. My parameters are upper triangular cholesky roots of some covariance matrix. To initializing, I need to put the parameter values in the position of upper triangular.

array([[ a,  b,  c],
       [ 0,  d,  e],
       [ 0,  0,  f]])
like image 749
News_is_Selection_Bias Avatar asked Oct 25 '25 21:10

News_is_Selection_Bias


1 Answers

I had the same question, so I didn't want to leave this one without an answer. Based on the suggestions by @DSM I created the function below:

import numpy as np

def create_upper_matrix(values, size):
    upper = np.zeros((size, size))
    upper[np.triu_indices(3, 0)] = values
    return(upper)

c = create_upper_matrix([1, 2, 3, 4, 5, 6], 3)
print(c)

This could be improved by adding functionality that infers the size of the required matrix from the data, but for now it relies on the user providing that information.

like image 142
MatAff Avatar answered Oct 27 '25 09:10

MatAff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!