error while coding without using conv

2 views (last 30 days)
Soumi Basu
Soumi Basu on 23 Mar 2015
Answered: Walter Roberson on 6 May 2015
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;

Answers (1)

Walter Roberson
Walter Roberson on 6 May 2015
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!