clear all;
clc;
%% wavelet transform
%产生一个平稳信号
% fs = 500; %采样频率
% Ts = 1/Fs; %采样间隔
% N=1028; %采样点数
% t = 0:Ts:N/fs; %采样时刻
% x = cos(2*pi*10*t)+cos(2*pi*25*t)+cos(2*pi*50*t)+cos(2*pi*100*t);
%产生一个非平稳信号
f1 = 10;
f2 = 25;
f3 = 50;
f4 = 100;
fs = 500;
N = 500;
t1 = 0:1/fs:0.3;
x1 = cos(2*pi*f1*t1);
t2 = 0.3+1/fs:1/fs:0.6;
x2 = cos(2*pi*f2*t2);
t3 = 0.6+1/fs:1/fs:0.8;
x3 = cos(2*pi*50*t3);
t4 = 0.8+1/fs:1/fs:1;
x4 = cos(2*pi*100*t4);
x5 = [x1 x2 x3 x4];
t5 = [t1 t2 t3 t4];
% x5= x5 + randn(size(t5)); % 加噪声
%% FFT 变换
xx = fft(x5);
y=abs(xx); %取模
y = y/(N/2); %换算成实际的幅度
y(1) = y(1)/2;
F = ([1:N]-1)*fs/N;
%% 一维离散小波分解
% [CA,CD]=dwt(x5,'db4')% 一维离散小波变换
% %对信号X进行单层分解,求得的近似系数存放在数组cA中,细节系数存放在数组cD
% y=idwt(CA,CD,'db4'); %一维离散小波反变换
% figure
% subplot(221);
% plot(x5); %画出波形图
% title('Original signal');
% grid on;
% subplot(222);
% plot(CA); %画出波形图
% title('MATLAB低频部分dwt-CA');
% grid on;
% subplot(223);
% plot(CD); %画出波形图
% title('MATLAB高频部分dwt-CD');
% grid on;
% subplot(224);
% plot(y); %画出波形图
% title('MATLAB重构idwt');
% grid on;
%% 一维信号的多层分解
[C,L]=wavedec(x5,3,'db6')
% ca1=appcoef(C,L,'db6',1);%近似系数抽取
% ca2=appcoef(C,L,'db6',2);
% ca3=appcoef(C,L,'db6',3);
% cd=detcoef(C,L,'db6',1);%细节系数抽取
% cd1=cell2mat(cd(1));
% cd2=cell2mat(cd(2));
% cd3=cell2mat(cd(3));
%将给定的小波系数一次性完全重建出信号
% X = waverec(C,L,'db6');
% figure
% plot(X);
% grid on;
%利用C,L等数据信息,单支重构信号的概貌系数,得到原信号在该系数对应的尺度下的信号分量,其长度与原信号一致。
%它重建的是原信号在指定层次的,高频或者低频分量
%重构1~3层低频信号
a1=wrcoef('a',C,L,'db6',1);
a2=wrcoef('a',C,L,'db6',2);
a3=wrcoef('a',C,L,'db6',3);
%重构第1~3层高频细节信号
d1=wrcoef('d',C,L,'db6',1);
d2=wrcoef('d',C,L,'db6',2);
d3=wrcoef('d',C,L,'db6',3);
%重构原始信号
XX = a1+a2+a3+d1+d2+d3;
figure
plot(XX);
grid on;
figure;
subplot(4,2,1);
plot(x5);
xlabel('Samples(a)','Fontname','Times New Roman');
ylabel('Amplitude','Fontname','Times New Roman');
grid on;
subplot(4,2,2);
plot(F(1:N/2),y(1:N/2));
xlabel('Samples(b)','Fontname','Times New Roman');
ylabel('Amplitude','Fontname','Times New Roman');
grid on;
subplot(4,2,3);
plot(a1);
ylabel('ca1','Fontname','Times New Roman');
grid on;
subplot(4,2,4);
plot(d1);
ylabel('cd1','Fontname','Times New Roman');
grid on;
subplot(4,2,5);
plot(a2);
ylabel('ca2','Fontname','Times New Roman');
grid on;
subplot(4,2,6);
plot(d2);
ylabel('cd2','Fontname','Times New Roman');
grid on;
subplot(4,2,7);
plot(a3);
ylabel('ca3','Fontname','Times New Roman');
grid on;
subplot(4,2,8);
plot(d3);
ylabel('cd3','Fontname','Times New Roman');
grid on;