How to use xcorr and findpeaks function for matrix operation

3 views (last 30 days)
I want to use matrix to operate, but this function can only use vector to operate. Is there any other function or method that can be replaced?
And I don't want to do it with the for loop.I guess it's faster to use matrix.
the code as follows.
s1 , s2; %s1, s2 512 * 905 matrix.
for i = 1:905;
[a,b] = xcorr(abs(s1(:,i)),abs(s2(:,i)));
[m,n] = findpeaks(abs(a)/max(abs(a)),b,'MinPeakHeight',0.999999999);
end
Do you have any answer ? thank you very much.

Answers (1)

Soumya
Soumya on 13 Aug 2025
I understand you’re working with two large datasets, s1 and s2, where each column is its own signal. Right now, you’re looping over all the columns to take the absolute value of each signal, run a cross-correlation, normalize the result, and then call findpeaks to detect very high peaks. A more efficient way to handle this is to replace the explicit loop with a combination of mat2cell and cellfun. The mat2cell function splits your matrices into cell arrays where each cell contains a single column (signal), and cellfun then applies a given function, in your case, xcorr followed by findpeaksto each corresponding pair of cells. This approach eliminates the visible for loop and can significantly reduce runtime by letting MATLAB handle the iteration internally.
You can refer to the following steps to achieve the same:
  • Split each matrix into cell arrays of column vectors:
C1 = mat2cell(abs(s1), M, ones(1, C));
C2 = mat2cell(abs(s2), M, ones(1, C));
  • Apply ‘xcorr’ to each pair of corresponding columns and normalize the output:
corrCells = cellfun(@(a, b) xcorr(a, b), C1, C2, 'UniformOutput', false);
normCorrCells = cellfun(@(r) abs(r) / max(abs(r)), corrCells, 'UniformOutput', false);
  • Use ‘findpeaks’ on each normalized result:
[pksCells, locsCells] = cellfun(@(r) findpeaks(r, lags, 'MinPeakHeight', 0.999999999), normCorrCells, 'UniformOutput', false);
When comparing both approaches, the execution time clearly shows the performance advantage of this method over the explicit loop:
Please refer to the following documentations to get more information on the given functions:
I hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!