The above error is a flaw in the code. The programmer forgot to include a check for what happens during shifting of signal when the peak index is too small or too large (i.e., at the edges of the matrix).
One could include the following code just before the shifting to bypass all peaks near the edges. Just define number of elements to ignore on each edge.
% check if index too big
if ipeak >= length(y)-numElements
% check if index too small
if ipeak <= numElements