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
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.
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 .
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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With