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 件のコメント
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!

Community Treasure Hunt

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

Start Hunting!

Translated by