There is no point in defining n when it always has exactly the same value as the loop iteration variable i. Get rid of one of those variables.
Your code is buggy because you did not consider that when you remove elements from a vector it gets smaller, which is clear if you print the vector on each loop iteration. This is what your code does:
- iteration -> remove nothing [1 8 5 9]
- iteration -> remove 2nd value [1 5 9]
- iteration -> remove nothing [1 5 9]
- iteration -> remove 4th value [1 5 9] !!! EEROR: the vector does not have a 4th element !!!
What do you expect to happen when you try to remove the 4th element of a 3-element vector?
You can resolve this by looping over the vector in reverse:
for n = numel(y):-1:1
Or by getting rid of the loop and writing simpler, more efficient MATLAB code using basic indexing: