% worksheet 7
% get signal
load train
N = 256;
X = y(1:N);
X = X(:); % force a column

% compute wavelet transform
[la,ha,ls,hs] = wfilters('db3')
[CA,CD] = dwt(X,la,ha,'mode','per');
w1X = [CA;CD];

% question 1
figure(1)
plot(w1X);
disp('Press a key')
pause


%question 2
% compute inverse
Y = idwt(CA,CD,ls,hs,'mode','per');
U = X-Y;
engergy_of_diff = U'*U/N
disp('Press a key')
pause


% question 3
%compare energy
wX = [CA;CD];
energy_X = X'*X/N
energy_w1X = w1X'*w1X/N
disp('Press a key')
pause


% question 4
% approximation and details
Z1 = zeros(size(CA)); 
XA = idwt(CA,Z1,ls,hs,'mode','per');
XD = idwt(Z1,CD,ls,hs,'mode','per');
figure(2)
plot(1:N,X,1:N,XA,1:N,XD);
U = X-XA-XD;
energy_of_diff = U'*U/N
disp('Press a key')
pause


% question 5
% frequencies
safXA = abs(fft(XA));
safXD = abs(fft(XD));
figure(3)
plot(1:N,safXA,1:N,safXD)
disp('Press a key')
pause

% question 6 some answers
% two stage
[CAA,CAD] = dwt(CA,la,ha,'mode','per');
w2X = [CAA;CAD;CD];
Z2 = zeros(size(CAA)); 
XCAA = idwt(CAA,Z2,ls,hs,'mode','per');
XAA = idwt(XCAA,Z1,ls,hs,'mode','per');
XCAD = idwt(CAD,Z2,ls,hs,'mode','per');
XAD = idwt(XCAD,Z1,ls,hs,'mode','per');

figure(5);
subplot(2,1,1)
plot(w2X);
subplot(2,1,1)
plot(1:N,X,1:N,XAA,1:N,XAD,1:N,XD);
disp('Press a key')
pause

safXAA = fftshift(abs(fft(XAA)));
safXAD = fftshift(abs(fft(XAD)));
safXD  = fftshift(abs(fft(XD)));
figure(6)
plot(1:N,safXAA,1:N,safXAD,1:N,safXD), 




