Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 1d array to lower triangular matrix

I would like to convert a 1 dimensional array into a lower, zero diagonal matrix while keeping all the digits.

I am aware of numpy.tril function, but it replaces some of the elements with zeros. I need to expand the matrix to contain all the original digits.

For example:

[10,20,40,46,33,14,12,46,52,30,59,18,11,22,30,2,11,58,22,72,12]

Should be

0
10 0
20 40 0
46 33 14 0
12 46 52 30 0
59 18 11 22 30 0
2 11 58 22 72 12 0
like image 455
Panos Kal. Avatar asked Jul 20 '18 09:07

Panos Kal.


People also ask

How do you turn a matrix into a lower triangular matrix?

If rows = cols, traverse the array a using two loops where outer loop represents the rows, and inner loop represents the columns of the array a. To convert given matrix to lower triangular matrix, set the elements of the array to 0 where (j > i) that is, the column number is greater than row number.

How do you convert a matrix into a lower triangular matrix in Matlab?

L = tril( A ) returns the lower triangular portion of matrix A . L = tril( A , k ) returns the elements on and below the kth diagonal of A .

How can you store an upper triangular matrix in one dimensional array?

When an upper-triangular matrix is stored in upper-triangular-packed storage mode, the upper triangle of the matrix is stored, including the diagonal, in a one-dimensional array. The upper triangle is packed by columns.


Video Answer


1 Answers

You could also use the numpy function np.tril_indices:

arr = np.array([10,20,40,46,33,14,12,46,52,30,59,18,11,22,30,2,11,58,22,72,12])
n = int(np.sqrt(len(arr)*2))+1

Generate zeros matrix and fill the lower part with your values:

idx = np.tril_indices(n, k=-1, m=n)
matrix = np.zeros((n,n)).astype(int)
matrix[idx] = arr
array([[ 0,  0,  0,  0,  0,  0,  0],
       [10,  0,  0,  0,  0,  0,  0],
       [20, 40,  0,  0,  0,  0,  0],
       [46, 33, 14,  0,  0,  0,  0],
       [12, 46, 52, 30,  0,  0,  0],
       [59, 18, 11, 22, 30,  0,  0],
       [ 2, 11, 58, 22, 72, 12,  0]])
like image 50
Brenlla Avatar answered Sep 20 '22 02:09

Brenlla