在 Numpy 中建立上三角為零的下三角矩陣
要建立一個上三角為零的下三角矩陣,可以使用 Python Numpy 中的 **numpy.tri()** 方法。第一個引數是陣列的行數,第二個引數是陣列的列數。
tri() 函式返回一個數組,其下三角部分填充為 1,其他部分填充為 0;換句話說,當 j <= i + k 時,T[i,j] == 1,否則為 0。
步驟
首先,匯入所需的庫 -
import numpy as np
建立上三角為零的下三角矩陣,使用 numpy.tri() -
arr = np.tri(4, 4)
顯示陣列 -
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 zero above the main diagonal forming a lower triangular matrix, 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
arr = np.tri(4, 4)
# 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. 0. 0. 0.] [1. 1. 0. 0.] [1. 1. 1. 0.] [1. 1. 1. 1.]] Array datatype... float64 Array Dimensions... 2 Our Array Shape... (4, 4) Elements in the Array... 16
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP