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

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 个评论

If you have a license for the Symbolic Math Toolbox, the closed-form expression for y can be obtained using syms, rectangularPulse, and int

请先登录,再进行评论。

 采纳的回答

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 个评论

Dear @Manikanta Aditya, just a suggestion: change "delta_t" to 0.01. Because the result is clear visible with 0.01 and an old beast (as my pc) takes minutes to finish. ;)
Just forgotten, your contribution is very helpful to understand convolution. Thanks.
Thank you for your kindness. It was really helpful to me!!

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by