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 ExchangePlatform 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