在Numpy中建立主對角線上方為1,其他位置為0的陣列


要建立一個主對角線上方為1,其他位置為0的陣列,可以使用Python Numpy中的**numpy.tri()**方法。

  • 第一個引數是陣列的行數。

  • 第二個引數是陣列的列數。

  • 第三個引數'k'是填充陣列的子對角線及其下方的位置。

k = 0為主對角線,k < 0在其下方,k > 0在其上方。預設值為0。tri()函式返回一個數組,其下三角形填充為1,其他位置為0;換句話說,當j <= i + k時,T[i,j] == 1,否則為0。

步驟

首先,匯入所需的庫:

import numpy as np

現在,建立一個主對角線上方為1,其他位置為0的陣列,使用numpy.tri()方法:

arr = np.tri(4, 4, k = 1)

顯示陣列:

print("Array...
",arr)

獲取資料型別:

print("
Array datatype...
",arr.dtype)

獲取陣列的維度:

print("
Array Dimensions...
",arr.ndim)

獲取陣列的形狀:

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素個數:

print("
Elements in the Array...
",arr.size)

示例

import numpy as np

# To create an array with ones above the main diagonal and zeros elsewhere, use the numpy.tri() method in Python Numpy
# The 1st parameter is the number of rows in the array
# The 2nd parameter is the number of columns in the array
# The 3rd parameter 'k' is the sub-diagonal at and below which the array is filled.
# The k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0.
arr = np.tri(4, 4, k = 1)

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size)

輸出

Array...
[[1. 1. 0. 0.]
[1. 1. 1. 0.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

Array datatype...
float64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

更新於:2022年2月10日

617 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.