error while coding without using conv

i have been trying to convolve x and h, using this code and getting the error "Attempted to access y(-10.01); index must be a positive integer or logical." I have to attain convolution without using conv or any predefined function.
clear all
clc
Fs = 100;
dt = 1/Fs;
StartTime = -5;
StopTime = 5;
t = StartTime:dt:StopTime;
x = heaviside(t);
% subplot (2,1,1), plot (t,x)
% axis ([-10 10 -3 3])
% grid on
% xlabel ('time');
% ylabel('unit step function');
a = heaviside (t-3);
b = heaviside (t+2);
h = a+b;
% subplot (2,1,2), plot (t,h)
% axis ([-10 10 -3 3])
% grid on
% xlabel ('time');
% ylabel('impulse');
for (i= -10:0.01:10)
y = 0;
for (j= -10:i)
if(i-j+0.01>0)
y(j)=y(j-0.01)+x(j)*h(j-0.01);
else
end
end
end
plot (t,y);
grid on;

답변 (1개)

Walter Roberson
Walter Roberson 2015년 5월 6일

0 개 추천

You are attempting to index an array by value, such as -10. You need to index by a positive integer instead.
For example (but check the boundary conditions)
xvals = -10 : 0.01 : 10;
numx = length(xvals);
for xidx = 1 : numx
y = zeros(1, xidx);
for yidx = 2 : xidx
if xidx + 1 > jidx
y(yidx) = y(yidx-1) + xvals(xidx) * h(xvals(yidx - 1));
end
end
end
but you really need to rethink the idea of always re-initializing y inside the first loop (the "for i" loop in your code), as otherwise the value of y at the end will be only whatever it got assigned on the very last pass, in which case you might as well only execute the last pass and skip the rest.

카테고리

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

질문:

2015년 3월 23일

답변:

2015년 5월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by