[英]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.我想创建一个 python 程序,该程序从具有一些系数的向量计算矩阵。 This matrix is some kind of an Lower and Upper triangular.
这个矩阵是某种下三角和上三角。 So lets say we have the following vector of coefficients a = [a0, a1, a2, a3, a4, a5], then I want to compute the matrix:
所以假设我们有以下系数向量 a = [a0, a1, a2, a3, a4, a5],然后我想计算矩阵:
I need to go from vector a to creating a lower/upper triangular matrix A. I know how to index it manually, but I need a program that can do it instead.我需要从向量 a 到创建一个下/上三角矩阵 A。我知道如何手动索引它,但我需要一个可以代替它的程序。
I was maybe thinking about a loop inside another loop but I struggle with how it is done in python, what do you think should be done here?我可能正在考虑另一个循环中的循环,但我对它在 python 中的完成方式感到困惑,你认为应该在这里做什么?
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.]]
Here is an approach using np.roll
, np.stack
, np.tril
and np.diag
.这是一种使用
np.roll
、 np.stack
、 np.tril
和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 diagonal
b[:,: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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.