pythonmatrix

How to create an upper triangular 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]])

Solution

  • 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.