# How to use MATLAB's $\tt xcorr$ to find index of a section inside a whole recording?

Trying to find the index offset of a short section of an audio I have taken out of my recording with cross-correlation, but this method sometimes succeeds finding the index of the short section sometimes fails, seems that it depends which sections are being compared and the length of the section made.

My question is what makes the xcorr lose its accuracy ? And if is it dependable ?

clear all;
close all;

offset=36644-(784/2); % here I define the offset for my selection.

B=A(offset:offset+784); %here I make selection from A 784 samples long...

[c,lags] = xcorr(A,B);  % c is the correlation, should have a clear peak

c=c((round(length(c)/2):round(length(c)))); %positive coefficients

[ff,ind]=max(c); % finding the index of the offset

M=A(ind:ind+(length(B))-1); % the selection from A based on the new index

plot(B);
hold;
plot(M);

• what does "fails" imply? What do you get? What did you expect? What have you tried to solve this? – Marcus Müller Nov 23 '16 at 14:49
• The chunks that I have selected in the beginning don't match based on the index points xcorr calculates, I think my question is pretty explenitory...if you run the code I have posted you would see that the graph shows two different sections being plotted, if you need more info please let me know. – skyisfalling Nov 23 '16 at 16:13
• Sorry, it's not self-explanatory. You need to try and understand why your code misbehaves. We're not doing your matlab debugging for you – we will try to help with the signal processing questions that arise underway! – Marcus Müller Nov 23 '16 at 16:17
• I believe cross correlation is a form of dsp, and if the code fails that wouldn't necessarily mean it is not a dsp question, you just don't understand this question...It is not debuging it is an answer why would cross correlation would fail for certain chunks of the signal being selected and not the other selections...Let me know if you need more info... – skyisfalling Nov 23 '16 at 16:41
• Seriously, we do not solve your problems for free, we try to help you be able to solve them yourself – and if you took a second to think about why something might have a higher cross-correlation with something else than with itself, you might have noticed what @texture now did for you, but did not explain. – Marcus Müller Nov 23 '16 at 16:43

[ff,ind]=max(abs(c)); % finding the index of the offset