简体   繁体   English

在python中的100 x 100矩阵中,填充非对角线元素

[英]In matrix of 100 x 100 in python, filling the off diagonal elements

I'm trying to fill the off diagonal elements on a 100x100 matrix, as shown below in the matlab code, so how to duplicate it in python.我正在尝试填充 100x100 矩阵上的非对角元素,如下面的 matlab 代码所示,那么如何在 python 中复制它。

T=(2*t0*diag(ones(1,100)))-(t0*diag(ones(1,99),1))-(t0*diag(ones(1,99),-1))

So I know that the first terms of RHS will fill the diagonal of the matrix with the value 2*t0 ,所以我知道 RHS 的第一项将用值2*t0填充矩阵的对角线,

which I do in python as follows:我在python中做的如下:

x = np.zeros((100,100))
np.fill_diagonal(x,2*t0)

but I don't know how to do the 2nd and the 3rd terms, I know that they will fill the values above and below the diagonal elements with value of -t0 , not all the off diagonal values but only filling the upper and lower value of diagonal with -t0, rest all are zeros, but I don't know how to write the python code for it.但我不知道如何做第 2 项和第 3 项,我知道他们会用-t0的值填充对角元素上方和下方的值,不是所有的非对角线值,而是只填充上下值对角线与-t0,其余全部为零,但我不知道如何为其编写python代码。

I found this code:我找到了这个代码:

# diagonal with offset from the main diagonal
diag([1,2,3], k=1) 

will give output as:将输出为:

array([[0, 1, 0, 0],
[0, 0, 2, 0],
[0, 0, 0, 3],
[0, 0, 0, 0]])

but how to apply it for a large matrix as in the case of my problem?但是如何将它应用于大型矩阵,就像我的问题一样? I work in interactive python ie Anaconda, so which are the other packages that I can use for my problem?我在交互式 python 中工作,即 Anaconda,那么我可以使用哪些其他软件包来解决我的问题?

From what you supply here np.diag , it is easy to do:从你在这里提供的np.diag ,很容易做到:

a = np.ones((1, 100))[0]
b = np.ones((1, 99))[0]
m = np.diag(a, 0) + np.diag(b, -1) + np.diag(b, 1)

m here is the 100x100 tridiagonal matrix m这里是 100x100 三对角矩阵

Update:更新:

I found a link here on a similar problem, have a look as well.我在这里找到了一个关于类似问题的链接,也看看。

Try np.triu() and np.tril()试试np.triu()np.tril()

numpy.tril(m, k=0)

  Lower triangle of an array.
  Return a copy of an array with elements above the k-th diagonal zeroed.
  Parameters: m - array_like, shape (M, N), input array; k - int, optional

  Diagonal above which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.


 numpy.triu(m, k=0)

 Upper triangle of an array.
 Return a copy of a matrix with the elements below the k-th diagonal zeroed.

Example with a 3x3 matrix:使用 3x3 矩阵的示例:

a=np.array([1,2,3,4,5,6,7,8,9]).reshape(3,3)
print(a)
>>> array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]])

a_diag=np.tril(np.triu(a, k=0), k=0)
print (a_diag)

>>> array([[1, 0, 0],
          [0, 5, 0],
          [0, 0, 9]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM