clc; clear; close all;
%% (a) Convolution Implementation (Manual, No Built-in Functions)
% Define input sequence and impulse response from Slide 12
x = [1, 1, 1, 2, 2, 2, 3, 3]; % Input sequence
h = [1, 3, 2, 1];
% Correct impulse response
% Manual Convolution Implementation
Nx = length(x);
Nh = length(h);
Ny = Nx + Nh - 1;
% Output length
y_manual = zeros(1, Ny);
% Initialize output
for n = 0 : Ny-1
% Iterate over output indices (0-based)
for k = 0 : Nh-1
% Iterate over impulse response indices
if (n - k >= 0) && (n - k < Nx)
y_manual(n+1) = y_manual(n+1) + x(n - k + 1) * h(k + 1);
end
end
end
% Plot results
figure;
subplot(3,1,1); stem(0:Nx-1, x, 'filled'); title('Input Sequence x[n]');
xlabel('n'); ylabel('x[n]');
subplot(3,1,2); stem(0:Nh-1, h, 'filled'); title('Impulse Response h[n]');
xlabel('n'); ylabel('h[n]');
subplot(3,1,3); stem(0:Ny-1, y_manual, 'filled'); title('Output Sequence y[n]
(Manual Convolution)'); xlabel('n'); ylabel('y[n]');
%% (b) Difference Equation Implementation (Non-Recursive, No Built-in
Functions)
% Define Coefficients (From Assignment)
B = [1, -2, -1, -1, -2]; % Coefficients for x[n]
% Output length (Same as x since it's non-recursive)
Ny = length(x);
y_diff = zeros(1, Ny); % Initialize output
% Implement Difference Equation Manually (Non-Recursive)
for n = 1:Ny
% Compute feedforward part (depends on x)
for k = 1:length(B)
if (n-k+1) > 0
y_diff(n) = y_diff(n) + B(k) * x(n-k+1);
end
end
end
% Plot difference equation results
figure;
stem(0:Ny-1, y_diff, 'filled'); title('Output Sequence y[n] (Difference
Equation, Non-Recursive)'); xlabel('n'); ylabel('y[n]');