在 NumPy 中構建一個塊矩陣


要在 Python Numpy 中構建矩陣塊,請使用 numpy.block() 方法。最內層列表中的塊沿著最後一個維度(-1)連線,然後沿著倒數第二個維度(-2)連線,依此類推,直到到達最外層列表。

塊可以是任何維度,但不會使用正常規則進行廣播。相反,會插入大小為 1 的前導軸,以使各個塊的 block.ndim 相同。這主要用於處理標量,這意味著像 np.block([v, 1]) 這樣的程式碼是有效的,其中 v.ndim == 1。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立兩個 numpy 陣列。我們插入了 int 型別的元素-

arr1 = np.eye(2) * 2
arr2 = np.eye(3) * 2

顯示陣列 -

print("Array 1...
", arr1) print("
Array 2...
", arr2)

獲取陣列的型別 -

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

獲取陣列的維度 -

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

獲取陣列的形狀 -

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

要在 Python Numpy 中構建矩陣塊,請使用 numpy.block() 方法 -

print("
Result...
",np.block([[arr1,np.zeros((2, 3))], [np.ones((3, 2)), arr2]]))

程式碼示例

import numpy as np

# Creating two numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.eye(2) * 2
arr2 = np.eye(3) * 2

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To build a block of matrix, use the numpy.block() method in Python Numpy print("
Result...
",np.block([[arr1,np.zeros((2, 3))], [np.ones((3, 2)), arr2]]))

輸出

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

Array 2...
[[2. 0. 0.]
[0. 2. 0.]
[0. 0. 2.]]

Our Array 1 type...
float64

Our Array 2 type...
float64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 2)

Our Array 2 Shape...
(3, 3)

Result...
[[2. 0. 0. 0. 0.]
[0. 2. 0. 0. 0.]
[1. 1. 2. 0. 0.]
[1. 1. 0. 2. 0.]
[1. 1. 0. 0. 2.]]

更新於: 2022 年 2 月 17 日

3K+ 瀏覽

啟動你的 事業

完成課程獲得認證

開始
廣告