Home > Mobile >  Create lower triangular matrix from a vector in python
Create lower triangular matrix from a vector in python

Time:10-14

I want to create a python program which computes a matrix from a vector with some coefficients. So lets say we have the following vector of coefficients c = [c0, c1, c2] = [0, 1, 0], then I want to compute the matrix:

enter image description here

So how do I go from the vector c to creating a lower triangular matrix A. I know how to index it manually, but I need a program that can do it. I was maybe thinking about a for-loop inside another for-loop but I struggle with how it is done practically, what do you guys think should be done here?

CodePudding user response:

One way (assuming you're using plain arrays and not numpy or anything):

src = [0, 1, 0]
dst = [
    [ 
        src[i-j] if i >= j else 0
        for j in range(len(src))
    ] for i in range(len(src))
]

CodePudding user response:

You can try the following:

import numpy as np

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

It gives:

[[1. 0. 0. 0. 0.]
 [2. 1. 0. 0. 0.]
 [3. 2. 1. 0. 0.]
 [4. 3. 2. 1. 0.]
 [5. 4. 3. 2. 1.]]
  • Related