-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastConv.m
69 lines (51 loc) · 1.37 KB
/
fastConv.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function y = fastConv()
% Fast-convolution algorithm, computed via frequency-domain multiplication
% of time-domain input signals x and h
% -------------------------
% Gregor McWilliam
% Clear screen
clc
close all
% Preconfigured input arguments for ease of use
[x, xx] = audioread("snare.wav");
[h, fs] = audioread("ir.wav");
x = x(:, 1);
h = h(:, 1);
x = x';
h = h';
% Define N as length of longest array, x or h, then zero-pad shorter
% signal to length N so that element-wise multiplication can be computed
if length(x) >= length(h)
N = length(x);
h = [h, zeros(1, N - length(h))];
else
N = length(h);
x = [x, zeros(1, N - length(x))];
end
% Generate window
win = rectwin(N)';
% Apply window to input x
x = x .* win;
% % Optional: custom DFT calculation
% % Generate zero-valued arrays for frequency-domain conversion
% X = zeros(1, N);
% H = zeros(1, N);
%
% % Compute the DFT of x and h
% for m = 0 : N-1
% for n = 0 : N-1
% X(m+1) = X(m+1) + x(n+1) * (exp(-1j * 2*pi * m/N * n));
% H(m+1) = H(m+1) + h(n+1) * (exp(-1j * 2*pi * m/N * n));
% end
% end
X = fft(x);
H = fft(h);
% Multiply DFT(x) with DFT(h), equivalent to time-domain convolution
Y = X .* H;
% Compute the IDFT of Y, returning the equivalent of the time-domain
% convolution of x and h
y = ifft(Y);
% Remove 0i imaginary unit for readabilty
y = real(y);
sound(y, fs);
end