%--------------------------------------------------
% Tony Hyun Kim
% 6.003: PS#7, Matlab exercise
%--------------------------------------------------

%--------------------------------------------------
% Part (a)
%--------------------------------------------------
n = [-31:32];
h = sin(pi*(n-1/2))./(pi*(n-1/2));
stem(n,h);
xlabel('n');
ylabel('h[n]');
title('Part (a): Impulse response of half-sample delay system');

%--------------------------------------------------
% Part (d)
%--------------------------------------------------
n = [-127:127];
x = sinc(n/8);
y = conv(x,h);

%--------------------------------------------------
% Part (e)
%--------------------------------------------------
% y[n] does not attain a maximum value at a unique 
% sample. By inspection y[0] and y[1] have the same
% maximum value. Notably, this maximum is not 1, as 
% in x[n] but 0.9936.
%--------------------------------------------------
subplot(211);
stem(n,x);
xlabel('n');
ylabel('x[n]');
title('Part (e): x[n], input to the half-delay system');

n = [-158:159];
subplot(212);
stem(n,y);
xlabel('n');
ylabel('y[n]');
grid on;
title('y[n], the output of the half-delay system');

%--------------------------------------------------
% Part (f)
%--------------------------------------------------
% y2 has a unique maximum at n = 1. The two signals
% are related by an integer delay (of one).
%--------------------------------------------------
y2 = conv(y,h);

n = [-127:127];
subplot(211);
stem(n,x);
xlabel('n');
ylabel('x[n]');
title('Part (f): x[n], input to the cascaded half-delay system');

n = [-189:191];
subplot(212);
stem(n,y2);
xlabel('n');
ylabel('y_2[n]');
grid on;
title('y_2[n], the output of the twice-cascaded half-delay system');

% Compute the impulse response of the cascaded system, h2
% The result is an impulse at n = 1. This is to be expected for
% a system that will delay the DT signal by 1 unit, as we have 
% observed with y2.
h2 = conv(h,h);
n = [-62:64];
figure;
stem(n,h2);
xlabel('n');
ylabel('h_2 = conv(h,h), where h is the impulse response of half-sample delay');

%--------------------------------------------------
% Part (g), see my handwritten work
%--------------------------------------------------

%--------------------------------------------------
% Part (i)
%--------------------------------------------------

% Define yc to be the half-unit delay of the input signal x(t). 
% I use the expression derived from part (g)
t = linspace(-158,159,4000);
yc = zeros(1,length(t));
for k = -127:127
    yc = yc + x(k+128)*sinc(t-1/2-k); % The additional -1/2 is the delay
end
figure;
plot(t,yc);
hold on;
n = [-158:159];
stem(n,y,'r');
xlabel('t/n');
ylabel('yc(t) and y[n]');
title('Problem (i): Note that y[n] is indeed the samples of the delayed continuous signal yc(t)');