Skip to content Skip to sidebar Skip to footer

Create Upper And Lower Triangular Matrix In Python

I want to create a python program that computes a matrix from a vector with some coefficients. This matrix is some kind of an Lower and Upper triangular. So lets say we have the fo

Solution 1:

You can try the following:

import numpy as np

c = [1, 2, 3, 4, 5, 6]
n = len(c)
m = 3
a = np.zeros((n,n))
for i in range(n):
    np.fill_diagonal(a[i:, :m], c[i])

np.fill_diagonal(a[:, m:], -1)    
print(a)

It gives:

[[ 1.  0.  0. -1.  0.  0.][ 2.  1.  0.  0. -1.  0.][ 3.  2.  1.  0.  0. -1.][ 4.  3.  2.  0.  0.  0.][ 5.  4.  3.  0.  0.  0.][ 6.  5.  4.  0.  0.  0.]]

Solution 2:

Here is an approach using np.roll, np.stack, np.tril and np.diag.

coeff = [1,2,3,4,5,6]
m = 3

nums = [np.roll(coeff,i) for i in range(m)] #get rolling ranges
a = np.tril(np.stack(nums).T) #stack -> transpose -> lower triangular
b = np.diag([-1]*m, m) #create matrix with offset diagonalb[:,:m] = a  #update offset matrix
print(b)
[[ 1  0  0 -1  0  0][ 2  1  0  0 -1  0][ 3  2  1  0  0 -1][ 4  3  2  0  0  0][ 5  4  3  0  0  0][ 6  5  4  0  0  0]]

Post a Comment for "Create Upper And Lower Triangular Matrix In Python"