set(groot,'defaultStemLineWidth',2);
clf;

M = 10;
L = 5;
x = @(n) 1.2*(n>=0 & n<M);
h = @(n) ((L-n)/L).*(n>=0 & n<L);
if 1;
    N = M; % no zero padding
else
    N = M + L - 1 ; % zero padding
end

nlo = -(L+2);
nhi = max([L+M-1,N])+2;
klinear = [nlo:nhi];
kcirc = [0:N-1];

ylinear = zeros(N,1);
ylinear(1:M+L-1) = conv(x(0:M-1),h(0:L-1));
ycirc = real(ifft(fft(x(0:M-1),N).*fft(h(0:L-1),N)));
yl = @(n) (n>=0 & n<(L+M-1)).*ylinear(n+1);
yc = @(n) ycirc(n+1).*(n>=0 & n<N);

for n=0:N-1
    subplot(221);
    stem(klinear,x(klinear),'LineWidth',2);
    hold on;
    stem(klinear,h(n-klinear),'LineWidth',2);
    hold off;
    axis([nlo nhi -0.1 1.3]);
    grid on;
    title(['linear convolution at time n=',int2str(n)]);
    xlabel('k');
    
    subplot(222);
    stem(n,yl(n),'LineWidth',2);
    text(n,yl(n)+0.25,num2str(yl(n)));
    xlim([nlo nhi]);
    ylim([0 4]);
    hold on;
    grid on;
    title(['linear convolution output at time n=',int2str(n)]);
    xlabel('n');
    %ax2 = axis;
    
    subplot(223);
    stem(kcirc,x(kcirc),'LineWidth',2);
    hold on;
    stem(kcirc,h(mod(n-kcirc,N)),'LineWidth',2);
    hold off;
    axis([nlo nhi -0.1 1.3]);
    grid on;
    title(['circular convolution at time n=',int2str(n)]);
    xlabel('k');

    subplot(224);
    stem(n,yc(n),'LineWidth',2);
    text(n,yc(n)+0.25,num2str(yc(n)));
    xlim([nlo nhi]);
    ylim([0 4]);
    hold on;
    grid on;
    title(['circular convolution output at time n=',int2str(n)]);
    xlabel('n');
    %ax4 = axis;
    
    %mx = max([ax2(end), ax4(end)]);
    %subplot(222); ylim([-0.1 mx]);
    %subplot(224); ylim([-0.1 mx]);

    shg;
    pause;
end
subplot(222); hold off;
subplot(224); hold off;