% Harjoitus 4

% Problem 1
u = [zeros(1,100) ones(1,500) zeros(1,100)];

x = linspace(0,1,500);
s = [zeros(1,100) 100*x.*(x-1).*(x-0.2).*(x-0.7) zeros(1,100)];

plot(u)
ylim([-1 2])

figure
plot(s,'r')
ylim([-2 2])


% Problem 2

% Boxcar kernel
k1 = ones(1,100)/100;

% Hann window kernel
k2 = hann(100);

% Convolutions
c1 = conv(u,k1);
figure
plot(c1)

c2 = conv(u,k2);
figure
plot(c2)

c3 = conv(s,k1);
figure
plot(c3)

c4 = conv(s,k2);
figure
plot(c4)


% Problem 3 length of signals is 700
C1 = conmatrix(k1',700);
C2 = conmatrix(k2,700);

% Check the convolutions calculated using convolution matrix
figure
plot(c1' - C1*u')

figure
plot(c2' - C2*u')

figure
plot(c3' - C1*s')

figure
plot(c4' - C2*s')


% Problem 4

% Deconvolution using pseudoinverse
sol1 = C1\c1';
sol2 = C2\c2';
sol3 = C1\c3';
sol4 = C2\c4';

% Check the results
figure
plot(sol1'-u)

figure
plot(sol2'-u)

figure
plot(sol3'-s)

figure
plot(sol4'-s)


% Problem 5
% Add noise in the convolutions
nc1 = c1 + 0.01*randn(size(c1));
nc2 = c2 + 0.01*randn(size(c2));
nc3 = c3 + 0.01*randn(size(c3));
nc4 = c4 + 0.01*randn(size(c4));

% Solve noisy deconvolution
nsol1 = C1\nc1';
nsol2 = C2\nc2';
nsol3 = C1\nc3';
nsol4 = C2\nc4';

% Plot calculated solutions and true signals
figure
plot(nsol1)
hold on
plot(u,'r')
hold off

figure
plot(nsol2)
hold on
plot(u,'r')
hold off

figure
plot(nsol3)
hold on
plot(s,'r')
hold off

figure
plot(nsol4)
hold on
plot(s,'r')
hold off




