MATLAB: How to fix: Index Exceeds Matrix Dimensions

dimensionserrorindexindexingmatrixsine wavespike sortingspikesorting

Hi,
Im new to MATLAB and am trying to extract data from a sine wave. I've set the threshold to -1 SD and want all of the data below it to stack into one matrix. In other words, M has to be a stacked product of P. However, at the last part of the code it gives the error: Index Exceeds Matrix Dimensions. From what I understand, this means that length(P)+P(i)>length(noise). So the logical thing to do would be to make 'noise' bigger or P(i) smaller. However, I can't seem to get rid of the error. I was told not to index so far into P, but i have no idea how to do that. Hopefully someone can help me with this!
clear all
hold off
% parameters
srate=1000;
t=1:99/srate:10;
noiseAmplitude=2;
a=4;
f=4;
%signal
signal=a*sin(2*pi*f*t);
noise= signal + noiseAmplitude*randn(1,length(signal));
standdev=std(noise);
P=find(diff(noise<-standdev)==1);
for i=1:length(P)
M(i,:)=noise(P(i):P(i)+10); (<-- ERROR: index exceeds matrix dimensions)
end
plot(M)

Best Answer

P =
2 27 32 34 37 50 52 60 65 68 70 75 90
P+10
ans =
12 37 42 44 47 60 62 70 75 78 80 85 100
Therefore P+10 exceeds the size of noise, and is giving you the error.
How you go about fixing it depends what you want to achieve in those cases. This one would fill in the rightmost part of array M:
for i=1:length(P)
offset = min(10, size(noise,2)-P(i));
M(i,(end-offset):end)=noise(P(i):P(i)+offset);
end