%% function convolution_test close all set(0, 'DefaultAxesFontSize', 18) % t1 = linspace(-3, 3, 50); x1 = ones(size(t1)); x1(t1 < -1) = -1; x1(t1 > 1) = -2; % t2 = linspace(-2.5, 2, 20); x2 = sin(t2); % figure plot(t1, x1, 'p-', t2, x2, 'p-') title('signals before synchronization') legend('x1', 'x2', 'Location', 'best') % [T1, X1, T2, X2, T, d] = prepareX(t1, x1, t2, x2); % figure plot(T1, X1, 'p-', T2, X2, 'p-') title('signals after synchronization') legend('x1', 'x2', 'Location', 'best') % computing covolution using conv function tic X = d * conv(X1, X2); toc % computing covolution using fft function tic X1 = [X1 zeros(1, size(T, 2) - size(X1, 2))]; X2 = [X2 zeros(1, size(T, 2) - size(X2, 2))]; X1_f = fft(X1); X2_f = fft(X2); X_f = X1_f .* X2_f; Xf = d * real(ifft(X_f)); toc % figure plot(T, X, T, Xf, 'o') title('convolution of two signals') legend('using conv', 'using fft', 'Location', 'best') end %% function [T1, X1, T2, X2, T, d] = prepareX(t1, x1, t2, x2) d1 = t1(2) - t1(1); d2 = t2(2) - t2(1); d = min(d1, d2); % t1s = Quan(t1(1), d); t1s = t1s + d * onestep(t1(1) - t1s); t1e = Quan(t1(end), d); t1e = t1e - d * onestep(t1e - t1(end)); % t2s = Quan(t2(1), d); t2s = t2s + d * onestep(t2(1) - t2s); t2e = Quan(t2(end), d); t2e = t2e - d * onestep(t2e - t2(end)); % T1 = t1s : d : t1e; X1 = interp1(t1, x1, T1); % T2 = t2s : d : t2e; X2 = interp1(t2, x2, T2); % Ts = t1s + t2s; Te = t1e + t2e; T = Ts : d : Te; end %% function y = Quan(x, delta) y = delta * round(x / delta); end %% function y = onestep(x) y = 0.5 * (sign(x) + 1); end