% Understanding convolutions part2
% This is part 2 of the tutorial.
% In here, we implement discrete convolution between two arrays.
% We have two arrays of values of length N = 5
a = [1, 0.75, 0.5, 0.25, 0] ;
b = [1/3, 1/3, 1/3, 0, 0] ;
% We can check the values of the array for i >= 1 and i <= N. For instance
% a(2) and b(2)
fprintf('a(2) = %f\n', a(2));
fprintf('b(2) = %f\n', a(2));
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Convolution between a and b is defined as
% Inf
% y(i) = SUM a(k)*b(i - k)
% k=-Inf
%%% Implementing the loop for the sum of the elements of array 'a'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sum_a = 0;
N = length(a);
for k = 1 : N
sum_a = sum_a + a(k);
end
fprintf('sum of the elements of a is : %f\n', sum_a);
%% Exercise : compute the sum for array 'b'
% Solution: repeat the loop as above but loop over array b. Also make
% sure the variable storing th sum is initialized as zero %%%%%%%%%%%%
sum_b = 0; % initialize sum
N = length(b);
for k = 1 : N
sum_b = sum_b + b(k); % loop over b
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('sum of the elements of b is : %f\n', sum_b);
%%
% If we want get all the values of y(i) for all i, we need to compute a sum over
% k for each i.
% The expected length of y is length(a) + length(b) - 1
% Exercise : complete the code to perform convolution between 'a' and 'b'
% Important to keep in mind that arrays in matlab are indexed starting from 1.
% We need to adjust the indexes to account for this difference
Ny = length(a) + length(b) - 1;
y = zeros(Ny, 1);
for i = 0 : Ny - 1
% Compute sum for each y(i)
for k = 0 : N - 1
% Solution: compute the sum using y(i + 1) in the same way we use
% sum_a above. The sum runs over the product of a and the mirrored and shifted
% version of b %%%%%%%%
if (i - k) >= 0 && (i - k) < N % make sure the sume is calculated for valid indexes
y(i + 1) = y(i + 1) + a(k + 1)*b(i - k + 1) ;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%
end
end
figure(1)
stem(0:Ny-1, y)