4

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]])
MLE
  • 1,033
  • 1
  • 11
  • 30
  • Sorry, what output are you hoping for? [From your [1,2,3],...[10,11,12] input, I mean.] – DSM Apr 06 '17 at 00:57
  • @DSM, I have edited the question. – MLE Apr 06 '17 at 01:05
  • I tend to make an empty matrix and fill it using the indices, as [here](http://stackoverflow.com/questions/20055493/numpy-convert-an-array-to-a-triangular-matrix). Would that work? – DSM Apr 06 '17 at 01:08
  • @DSM, it seems working. Let me try again – MLE Apr 06 '17 at 01:21

1 Answers1

4

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.

Community
  • 1
  • 1
MatAff
  • 1,250
  • 14
  • 26