%Compression of Piecewise Linear using db2 Daubechies wavelet transformn.
%Also reconstruct piecewise linear from its wavelet transform (not in text).
%Construct Piecewise Constant Signal:
clear;X(1:5)=[-2:2];X(6:13)=[3:-0.5:-0.5];
X(14:23)=[-1:0.2:0.8];X(24:32)=[1:-0.3:-1.4];
figure,subplot(211),stem(X),axis tight,title('ORIGINAL SIGNAL')
%db2 Daubechies Scaling (G) and Wavelet (H) Functions:
G=[1+sqrt(3),3+sqrt(3),3-sqrt(3),1-sqrt(3)]/4/sqrt(2);
H=fliplr(G).*(-1).^[0:length(G)-1];L=length(G);
%1st Stage db2 Daubechies Wavelet Transform:
XX=[X(end-L+2:end) X];%Cyclic Pre-padding
X1=G(1)*XX(L:2:end-1)+G(2)*XX(L-1:2:end-2)+G(3)*XX(L-2:2:end-3)+G(4)*XX(L-3:2:end-4);
x1=H(1)*XX(L:2:end-1)+H(2)*XX(L-1:2:end-2)+H(3)*XX(L-2:2:end-3)+H(4)*XX(L-3:2:end-4);
%2nd Stage db2 Daubechies Wavelet Transform:
XX=[X1(end-L+2:end) X1];%Cyclic Pre-padding
X2=G(1)*XX(L:2:end-1)+G(2)*XX(L-1:2:end-2)+G(3)*XX(L-2:2:end-3)+G(4)*XX(L-3:2:end-4);
x2=H(1)*XX(L:2:end-1)+H(2)*XX(L-1:2:end-2)+H(3)*XX(L-2:2:end-3)+H(4)*XX(L-3:2:end-4);
figure,subplot(211),stem(X1),subplot(212),stem(x1),axis tight,...
title('1st STAGE: AVERAGE (TOP) AND DETAIL (BOTTOM)')
figure,subplot(211),stem(X2),subplot(212),stem(x2),axis tight,...
title('2nd STAGE: AVERAGE (TOP) AND DETAIL (BOTTOM)')
%Inverse Wavelet Transform of {X2,x2,x1}:
Z2=[X2 X2(1:2)];z2=[x2 x2(1:2)];%2nd Stage Reconstruction:
Z1A(1:2:2*length(x2))=G(1)*Z2(1:end-2)+G(3)*Z2(2:end-1);
Z1A(2:2:2*length(x2))=G(2)*Z2(2:end-1)+G(4)*Z2(3:end);
Z1B(1:2:2*length(x2))=H(1)*z2(1:end-2)+H(3)*z2(2:end-1);
Z1B(2:2:2*length(x2))=H(2)*z2(2:end-1)+H(4)*z2(3:end);
Z1=Z1A+Z1B;%Z1=X1.
Z1=[X1 X1(1:2)];z1=[x1 x1(1:2)];%1st Stage Reconstruction:
Z0A(1:2:2*length(x1))=G(1)*Z1(1:end-2)+G(3)*Z1(2:end-1);
Z0A(2:2:2*length(x1))=G(2)*Z1(2:end-1)+G(4)*Z1(3:end);
Z0B(1:2:2*length(x1))=H(1)*z1(1:end-2)+H(3)*z1(2:end-1);
Z0B(2:2:2*length(x1))=H(2)*z1(2:end-1)+H(4)*z1(3:end);
Z0=Z0A+Z0B;%Z0=X.
figure,subplot(211),stem(X),subplot(212),stem(Z0),...
title('ORIGINAL (TOP) AND RECONSTRUCTED (BELOW)')

