Index exceeds the number of array elements (4)

1 view (last 30 days)
Ethan
Ethan on 23 Feb 2021
Answered: Mahesh Taparia on 26 Feb 2021
I am trying to write a script that will convolve two arrays (without using the conv function, just flipping and shifting then multiplying signals), and i have my script mostly written, however have an issue when i have a large signal convolved with a smaller one. It seems that my issue is with how im indexing i or y, however i dont really see any issue with it. please let me know what im doing wrong.
x = repmat([1:10 9:-1:2],1,20);
n1 = -180:179;
h = [1 -1];
n2 = [0 1];
%define k across n1 and n2
k = min(n1)+min(n2):max(n1)+max(n2);
%length of signals
lx = length(x);
lh = length(h);
lk = length(k);
%signals to convolve
xk = [x, zeros(1,lx)];
hk = [h, zeros(1,lh)];
y = [zeros(1,lk)];
%loop to shift through h
for i = 1:(lx+lh)-1
y(i) = 0;
for n = 1:lh
if ((i-n)+1>0)
y(i) = y(i) + (xk(n) * hk(i-n+1));
end
end
end
this yeilds the error:
Index exceeds the number of array elements (4).
Error in Project1Discrete (line 53)
y(i) = y(i) + (xk(n) * hk(i-n+1));
however if i use a simpler input, like below, it runs and convolves just fine.
x = [2 -3];
n1 = [0 1];
h = [3 -1 4];
n2 = [-2 -1 0];
  2 Comments
Rik
Rik on 23 Feb 2021
Out of curiosity: why are you avoiding using conv? It is just about the most optimized function that takes an appreciable amount of time that I have seen so far. My region growing function works based on it, and it actually saturates as many cores as I have (especially for larger (e.g. 3D) data).
Ethan
Ethan on 23 Feb 2021
just a homework assignment... so have to see how convolution works behind the actual function

Sign in to comment.

Answers (1)

Mahesh Taparia
Mahesh Taparia on 26 Feb 2021
Hi
There was some error in the code. The error was there in assigning xk, hk and the range of n in the for loop. The below code will work.
x = repmat([1:10 9:-1:2],1,20);
n1 = -180:179;
h = [1 -1];
n2 = [0 1];
%define k across n1 and n2
k = min(n1)+min(n2):max(n1)+max(n2);
%length of signals
lx = length(x);
lh = length(h);
lk = length(k);
%signals to convolve
xk = [x, zeros(1,lh)];
hk = [h, zeros(1,lx)];
y = zeros(1,lk);
%loop to shift through h
for i = 1:(lx+lh)-1
% y(i) = 0;
for n = 1:lx
if ((i-n)+1>0)
y(i) = y(i) + (xk(n) * hk(i-n+1));
end
end
end
Moreover, you can use conv function to find convolution. Hope it will help!

Categories

Find more on Operators and Elementary Operations 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!