MATLAB: Over-lapping & adding [FFT] – Error – Index exceeds matrix dimensions

fft

Hello,
I am trying to process a signal using the overlap and add method, however I get an error, when running the loop, I am not sure what matrix is exceeding the dimensions or how to solve it, i tried adding counters to trace the issue but I still can't understand where i went wrong, here's the code:
clc;
clear all;
x = [3 9 1 2 3 4 5 6 3 4 5 6 7 8 9 8 7 8];
h = [1 2 1 1];
% Code to perform Convolution using Overlap Add Method
n1 = length(x);
% M-1
n2 = length(h);
% length of the output
N = n1+n2-1;
% intializing the output vector
y = zeros(1,N);
% zero padded impulse response
h1 = [h zeros(1,n2-1)]
% block size
n3 = length(h1);
% new size of output function
% now that we know the block size
y = zeros(1,N+n3-n2);
% FFT of the impulse response
%fft_size =
H = fft(h1); %, fft_size);
count_1 = 0;
count_2 = 0;
count_3 = 0;
count_4=0;
count_5=0;
for i = 1:n2:n1
if i<=(n1+n2-1)
x1 = [x(i:i+n3-n2) zeros(1,n3-n2)];
count_1 = count_1+1;
else
x1 = [x(i:n1) zeros(1,n3-n2)];
count_2 = count_2 +1;
end
x2 = fft(x1);
x3 = x2.*H;
x4 = round(ifft(x3));
if (i==1)
y(1:n3) = x4(1:n3);
count_3 = count_3+1;
else
y(i:i+n3-1) = y(i:i+n3-1)+x4(1:n3);
count_4 = count_4+1;
end
count_5 = count_5+1;
end

Best Answer

Maith - if I run your code as a function (named g13.m) or as a script, I observe the following error
Index exceeds matrix dimensions.
Error in g13 (line 33)
x1 = [x(i:i+n3-n2) zeros(1,n3-n2)];
So we know the line, but not which iteration. To make the debugging easier, run the following command before running your above code
dbstop if error
This will cause the debugger to pause at the line which generates the error, and you will be able to look at all variables at that point and so you can get an idea of what is happening. When I do this, I notice that this fails for when i is 17 (as an aside, you may want to use a different index variable name as i and j are also used to represent the imaginary number). The code then fails because of
x(i:i+n3-n2)
as i is 17, n3 is 7, and n2 is 4 with x only being a vector with 18 elements. With that in mind, how would you modify this code to handle the case where i+n3-n2 exceeds 18?
Related Question