Hi everyone,
I’m a beginner for neuronal spiking analysis.

I’m studying for that by reading Mike’s “MATLAB for Brain and Cognitive Scientists.” and that’s a very excellent book!

Now I’m struggling with autocorrelation.
In chapter 23 of that book, I don’t come up with a line of code at the part of the following code “in the % need an extra line of code here…
I understand there’s a problem in index of “spikes(si)-win:spikes(si)+win” because some indices have negative values.

Somebody help me with that?

In addition, what about using Matlab function xcorr for autocorrelation or cross corelation analysis? Any problems?

Thank you in advance.


%% spike timing with full matrices
win = 50; % in ms and also in indices (only in this dataset!)
spikerhyth = zeros(1,win*2+1);
n = 0;

for triali=1:trialnum

spikes = find(spikesfull(triali,:));
% need an extra line of code here...

for si=1:length(spikes)
    spikerhyth = spikerhyth + spikesfull(triali,spikes(si)-win:spikes(si)+win);
    n = n+1;
end % end spike loop

end % end trial loop

% divide by N to finalize average
spikerhyth = spikerhyth./n;

figure(2), clf
set(gca,‘xlim’,[-10 10])

Hi Hideki. You’ve identified the problem correctly: If a spike happens early or late in the window, the indexing will be outside the range and MATLAB will give an error.

I’ll give you a hint for fixing it. If you want to remove any spikes that happen in the first 10 time points, you can write
spikes(spikes<10) = [];
You can try to adapt that code for a certain number of points, and also to remove spikes at the end.

As for your second question, yes, you can definitely use the MATLAB xcorr or xcov functions. Don’t I also show that in the book? They mostly give the same results, with some possible differences around the boundaries, depending on how you specify the parameters for the two analyses.


Hi Mike,

Thanks a lot!
It’s very helpful.
Thanks to your hit, it works well!

About xcorr or xcov functions, I was just interested in which way is the most popular to use for autocorrelation analysis.