Index exceeds the number of array elements (4)

1 次查看(过去 30 天)
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 个评论
Rik
Rik 2021-2-23
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 2021-2-23
just a homework assignment... so have to see how convolution works behind the actual function

请先登录,再进行评论。

回答(1 个)

Mahesh Taparia
Mahesh Taparia 2021-2-26
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!

类别

Help CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by