Index exceeds the number of array elements (4)

조회 수: 2 (최근 30일)
Ethan
Ethan 2021년 2월 23일
답변: Mahesh Taparia 2021년 2월 26일
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에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by