使用Python返回兩個一維序列的離散線性卷積


要返回兩個一維序列的離散線性卷積,請在Python Numpy中使用numpy.convolve()方法。卷積運算子經常出現在訊號處理中,它模擬線性時不變系統對訊號的影響。在機率論中,兩個獨立隨機變數的和服從其各自分佈卷積的分佈。如果v比a長,則在計算之前交換陣列。

該方法返回a和v的離散線性卷積。第一個引數a (N,)是第一個一維輸入陣列。第二個引數v (M,)是第二個一維輸入陣列。第三個引數mode是可選的,其值為'full'、'valid'、'same'。模式'valid'返回長度為max(M, N) - min(M, N) + 1的輸出。卷積積只給出訊號完全重疊的點。訊號邊界外的值沒有影響。

預設模式為'full'。這將返回每個重疊點的卷積,輸出形狀為(N+M-1,)。在卷積的端點處,訊號不會完全重疊,可能會看到邊界效應。

步驟

首先,匯入所需的庫:

import numpy as np

使用array()方法建立兩個numpy一維陣列:

arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 1, 0.5])

顯示陣列:

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

檢查兩個陣列的維度:

print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

檢查兩個陣列的形狀:

print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

要返回兩個一維序列的離散線性卷積,請在Python Numpy中使用numpy.convolve()方法:

print("\nResult....\n",np.convolve(arr1, arr2, mode = 'full' ))

示例

import numpy as np

# Creating two numpy One-Dimensional array using the array() method
arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 1, 0.5])

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To return the discrete linear convolution of two one-dimensional sequences, use the numpy.convolve() method in Python Numpy
print("\nResult....\n",np.convolve(arr1, arr2, mode = 'full' ))

輸出

Array1...
[1 2 3]

Array2...
[0. 1. 0.5]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(3,)

Shape of Array2...
(3,)

Result....
[0. 1. 2.5 4. 1.5]

更新於:2022年2月28日

651 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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