-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convolution.m
76 lines (58 loc) · 1.46 KB
/
Convolution.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
69
70
71
72
73
74
75
76
%% Convolution of two signals
clear all, clc
% Create constants
a = linspace(-10,10,100);
b = linspace(-1,1,100);
t = linspace(0,3,100);
A = linspace(-6,6,100);
f = 512;
w = 2*pi*f;
% Initialize signals
f = a .* exp(-b.*t);
g = A .* sin(w*t);
%% Convolution with a built-in function
C = conv2(f,g,'same');
% Display functions and their convolution
figure(1),clf
plot(t,f, t,g, t,C)
legend({'a*e^(-bt)';'A*sin(wt)';'Conv2'})
%% Convolution in Time Domain
% Convolution sizes
n = length(f); % f and g have same sizes
nConv = 2*n - 1;
half = floor(n/2);
% flipped version of g
gflip = g(end:-1:1);
% zero-padded data for convolution
data = [ zeros(1,half) f zeros(1,half) ];
% initialize convolution output
Ctime = zeros(1,nConv);
% run convolution
for i=half+1:nConv-half
% get a chunk of data
chunk = data(i-half+1:i+half);
% compute dot product
Ctime(i) = sum( chunk.*gflip );
end
% cut off edges
Ctime = Ctime(half+1:end-half);
%% Convolution in Frequency Domain
% spectra of f and g
fSpec = fft(f,nConv);
gSpec = fft(g,nConv);
% element-wise multiply
fXg = fSpec .* gSpec;
% inverse FFT to get back to the time domain
Cfreq = ifft( fXg );
% cut off edges
Cfreq = Cfreq(half+1:end-half);
%% Visualize the Comparison
figure(2)
subplot(311)
plot(C,'r-'),legend('Built-in')
subplot(312)
plot(Ctime,'b-'),legend('Time domain')
subplot(313)
plot(Cfreq,'k-')
legend('Freq. domain')
%% end