簡體   English   中英

在python中的100 x 100矩陣中,填充非對角線元素

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

我正在嘗試填充 100x100 矩陣上的非對角元素,如下面的 matlab 代碼所示,那么如何在 python 中復制它。

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

所以我知道 RHS 的第一項將用值2*t0填充矩陣的對角線,

我在python中做的如下:

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

但我不知道如何做第 2 項和第 3 項,我知道他們會用-t0的值填充對角元素上方和下方的值,不是所有的非對角線值,而是只填充上下值對角線與-t0,其余全部為零,但我不知道如何為其編寫python代碼。

我找到了這個代碼:

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

將輸出為:

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

但是如何將它應用於大型矩陣,就像我的問題一樣? 我在交互式 python 中工作,即 Anaconda,那么我可以使用哪些其他軟件包來解決我的問題?

從你在這里提供的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這里是 100x100 三對角矩陣

更新:

我在這里找到了一個關於類似問題的鏈接,也看看。

試試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.

使用 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