MATLAB: Convolution of two piecewise signals returning zero (exercise 2 in attachment)

continuous timeconvolutionlti

Hello, I'm an absolute beginner at MATLAB and I've gotten as far as plotting the two functions, x(t) being the input signal and h(t) being the impulse response of an LTI system. I'm asked to write a code to solve and plot the output (convolution of x(t)*h(t)) but the convolution is coming as a straight zero line, please let me know if there's a way to convolute these functions appropriately (without referring to Laplace or such). Find question 2 in the attached file to understand better if needed.
t = -10:1/10:10;
x = zeros(length(t));
h = zeros(length(t));
y = zeros(length(t));
for i=1:numel(t)
if t(i)<0 || t(i)>2
x(i) = 0;
else
x(i) = sin(pi*t(i));
end
if t(i)<3 || t(i)>8
h(i) = 0;
else
h(i) = 1;
end
y(i) = conv(x(i),h(i));
end
plot (t,h,'r',t,x,'b',t,y,'k')

Best Answer

t = -10:1/10:10;
x = zeros(1,length(t));
h = zeros(1,length(t));
for i=1:numel(t)
if t(i)<0 || t(i)>2
x(i) = 0;
else
x(i) = sin(pi*t(i));
end
if t(i)<3 || t(i)>8
h(i) = 0;
else
h(i) = 1;
end
end
y = conv(x,h,'same');
% y = conv(x,h,'full') will create an y which has length(y) = length(x)+length(h)-1
plot (t,h,'r',t,x,'b',t,y,'k')
untitled.jpg