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

댓글을 달려면 로그인하십시오.

 채택된 답변

Manikanta Aditya
Manikanta Aditya 2024년 3월 30일
이동: Voss 2024년 3월 30일
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

Alexander
Alexander 2024년 3월 30일
편집: Alexander 2024년 3월 30일
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.
@Alexander, Thank you for the suggestation.
Thank you for your kindness. It was really helpful to me!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2024년 3월 30일

댓글:

2024년 3월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by