藍橋杯延期到9月中旬了……真地太難了…… T^T
最近舍友要寫一份與循環卷積有關的報告,需要寫python的循環卷積代碼,於是我就直接根據原理幫舍友用python實現了這個。
用的序列是x1=[1,2,3,4],x2=[1,1,1,1,0,0,0,0],以下是x1和x2的循環卷積的結果圖。
話不多說,放代碼了!
1 # -*- coding:utf-8 -*- 2 import numpy as np 3 import matplotlib.pyplot as plt 4 #x1=[6,5,6,3,5,7,0,1] 5 #x2=[7,1,2,9,4,3,20,1,2,3,5] 6 x1=[1,2,3,4] 7 x2=[1,1,1,1,0,0,0,0] 8 9 #確定循環卷積序列的長度N 10 N=max(len(x1),len(x2)) 11 12 #補0 13 if len(x1)>len(x2): 14 for i in range(len(x2),len(x1)): 15 x2.append(0) 16 else: 17 for i in range(len(x1),len(x2)): 18 x1.append(0) 19 20 #序列x1周期延拓,以y軸為對稱軸對稱變換,截取0~N-1的序列 21 temp_x1=[] 22 temp_x1.append(x1[0]) 23 for i in range(1,len(x1)): 24 temp_x1.append(x1[N-i]) 25 print(temp_x1) 26 27 #針對變化后的x1進行0~N-1的循環移動,獲得一個N*N的cycle_matrix矩陣 28 x1=temp_x1 29 cycle_matrix=[] 30 cycle_matrix.append(x1) 31 for step in range(1,N): 32 temp=[] 33 for i in range(0,N): 34 temp.append(0) 35 for i in range(0,N): 36 temp[(i+step)%N]=x1[i] 37 cycle_matrix.append(temp) 38 print(cycle_matrix) 39 40 #矩陣相乘,獲得循環卷積結果序列result 41 cycle_matrix=np.array(cycle_matrix) 42 x2=np.array(x2) 43 result=np.matmul(cycle_matrix,np.transpose(x2)) 44 result=list(result) 45 nnum=[] 46 for i in range(0,N): 47 nnum.append(i) 48 print(result,nnum) 49 50 #畫圖 51 plt.bar (nnum,result,width=0.04,color ='r') 52 plt.xlabel ('n') 53 plt.ylabel ('y') 54 plt.title ('result') 55 plt.show ()