简体   繁体   中英

Matlab:Xcorr operation without using for loops

I have two matrices A(2*1600*3) and B(2*1600). I am trying to do xcorr operation for each row in A against each row in B and want to store the results in a Matrix. At present I am using the following code.

for ii=1:3
    for jj=1:2
       X(ii,jj)=max((xcorr(A(jj,:,ii),B(jj,:)))); 
    end
end

Since I am using two for loops, it is consuming more time and is affecting the execution time of my entire program which already had a for loop. How can I do this without the two for loops and store the output in a matrix ?

Meanwhile, I have also tried the above code with cellfun for a single column of the output matrix.

`cellfun(@(x) max(xcorr(x, B(1,:))), A, 'UniformOutput', false);`

In my observation, for loop is much faster than cellfun. Execution times: For loop: 2.4 secs for two columns of matrix output. Cellfun:2.6 secs for one column of matrix output.

You can do this easily using fft . Cross-correlation is very similar to convolution:

% Compute the size of the cross-correlation.
N = size(A,2) + size(B,2) - 1;
% Do correlation using FFT.  We have to flip one of the inputs.
% If A and B are both symmetric, you might want to add the 'symmetric' flag to ifft
Y = ifft(fft(A,N,2) .* fft(flip(B,2),N,2), N, 2);
% Squeeze out the second dimension and transpose so it matches your size and shape.
Y = squeeze(max(Y, [], 2))'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM