MATLAB: Working around “Index exceeds matrix dimensions”

if statementindexindexingMATLAB

I am looking for peaks in a trace with the following code.
for i= 1:length(y)
if y(i) < -0.02 && y(i-1) > -0.02
c=c+1;
n(c,:)=abs(y(i:i+npts-1));
end
end
sometimes i get the error "Index exceeds matrix dimensions" if a peak happens at the end of the trace and there aren't enough points to populate the row in "n"
I would like to either ignore this peak or fill the the missing positions with zeros. Any suggestions on how?
Thanks

Best Answer

In case anyone is wondering I got around the issue with the following
if(y(i) >0.05 && y(i-1) < 0.05) &&( (length(y)-i >= npts))
if both conditions aren't met then it doesn't do anything.