How to make this code without using built-in convolution function.

12 visualizzazioni (ultimi 30 giorni)
clear all;
clc;
delta_t=0.0001;
t=[-6:delta_t:6];
x=(t>=-2)&(t<=2);
h=((t>=0)&(t<=3)).*((2/3)*t);
y=conv(x, h, 'same')*delta_t;
subplot(3,1,1); plot(t,x,'r'); grid on; ylim([-0.5 2]); ylabel('x(t)')
subplot(3,1,2); plot(t,h,'m'); grid on; ylim([-0.5 3]); ylabel('h(t)')
subplot(3,1,3); plot(t,y,'b'); grid on; ylim([-0.5 4]); ylabel('y(t)')
  1 Commento
Paul
Paul il 31 Mar 2024
If you have a license for the Symbolic Math Toolbox, the closed-form expression for y can be obtained using syms, rectangularPulse, and int

Accedi per commentare.

Risposta accettata

Manikanta Aditya
Manikanta Aditya il 30 Mar 2024
Spostato: Voss il 30 Mar 2024
To make the code without using the built-in convolution function, you can implement the convolution manually.
Check how you can do it:
clear all;
clc;
delta_t = 0.0001;
t = [-6:delta_t:6];
x = (t >= -2) & (t <= 2);
h = ((t >= 0) & (t <= 3)) .* ((2/3) * t);
% Manual Convolution
len_x = length(x);
len_h = length(h);
len_y = len_x + len_h - 1; % Length of the convolution output
y_manual = zeros(1, len_y); % Initialize the result array
% Perform the convolution operation manually
for i = 1:len_x
for j = 1:len_h
y_manual(i + j - 1) = y_manual(i + j - 1) + x(i) * h(j) * delta_t;
end
end
% To match the 'same' size as the built-in conv function, we need to trim the result
% Calculate the start and end indices to trim y_manual to the same size as x
start_index = floor(len_h / 2);
end_index = start_index + len_x - 1;
y_manual_same_size = y_manual(start_index:end_index);
subplot(3,1,1); plot(t, x, 'r'); grid on; ylim([-0.5 2]); ylabel('x(t)')
subplot(3,1,2); plot(t, h, 'm'); grid on; ylim([-0.5 3]); ylabel('h(t)')
subplot(3,1,3); plot(t, y_manual_same_size, 'b'); grid on; ylim([-0.5 4]); ylabel('y(t)')
Thanks!
  5 Commenti
whyyss
whyyss il 31 Mar 2024
Thank you for your kindness. It was really helpful to me!!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by