% E02_2.m                 27feb19   20feb20    06mar23
% Signal Generation, smoothing by a moving-average filter, interpolation
clear all; clf;

R = 50;
d = rand(R,1)-0.5;   % noise
m = 0:1:R-1;
s = 2*m.*(0.9.^m);   % signal
x  = s + d';                    % noisy signal
figure(1);
subplot(3,1,1);  stem(m,s);
xlabel('Time index n'); ylabel('Amplitude'); title('Original uncorrupted sequence');
subplot(3,1,2);  stem(m,d);
xlabel('Time index n'); ylabel('Amplitude');  title('Noise');
subplot(3,1,3);  stem(m,x);
xlabel('Time index n'); ylabel('Amplitude');  title('Corrupted sequence');

return;

%% moving average
figure(2);
plot(m,d,'r-',m,s,'b--',m,x,'k')
xlabel('Time index n'); ylabel('Amplitude')
legend('d[n]','s[n]','x[n]');

M = input('Number of input samples [2,10] = ');
b = ones(M,1)/M;
y = filter(b,1,x);
plot(m,x,'k-',m,y,'b--')
legend('x[n]','y[n]');
xlabel ('Time index n');ylabel('Amplitude');

%%  interpolators (L=2)
xx = [2 6 2 2 8 7 1 8 6 5];
xu = [xx; zeros(size(xx))];
xu = xu(:); xu = xu';

b0 = [1 1];   % simplest: hold filter
b1 = [.5 1 .5];       % linear average, length 3
b2 = [.15 0 .35 1 .35 0 .15];   % length=7, "reasonable" coeffs., =0 for original samples
b3 = [-.15 0 .65 1 .65 0 -.15]; % length 7, "sinc-like" [see also dip07_2.m]
                %-------------- note DCgain = 2 (= L) in all cases
y0 = filter(b0,1,xu);
y1 = filter(b1,1,xu);
y2 = filter(b2,1,xu);
y3 = filter(b3,1,xu);

y0s = y0; 
y1s = [y1(2:end) 0];  % shifted (advanced) for a clearer plot
y2s = [y2(4:end) 0 0 0];
y3s = [y3(4:end) 0 0 0];

figure(1);
subplot(511); stem(xu);
subplot(512); stem(y0s);
subplot(513); stem(y1s);
subplot(514); stem(y2s);
subplot(515); stem(y3s);

%%  if zero-crossings of sinc are not preserved...
%%% ...we perform "approximation" rather than interpolation
bb = [1 2 3 2 1];  bb = bb/sum(bb)*2;
yy = filter(bb,1,xu);
yys = [yy(3:end) 0 0];

figure(2);
subplot(311); stem(xu);
subplot(312); stem(y2s,'r'); hold on; stem([1:2:20],xu(1:2:end),'b'); hold off
subplot(313); stem(yys,'r'); hold on; stem([1:2:20],xu(1:2:end),'b'); hold off






