Vectorize application of xcorr() function

2 Ansichten (letzte 30 Tage)
Howard Wilton
Howard Wilton am 3 Dez. 2022
Bearbeitet: Bruno Luong am 6 Dez. 2022
For the following code,
t = 0:1e-3:1-1e-3;
AF_hat = [];
fd_ = -8:0.1:8;
for fd = fd_
AF_hat = [AF_hat; xcorr(s,s.*exp(-1i*2*pi*fd*t))*Ts];
end
I would like to eliminate the for loop by doing something like,
xcorr(s,s.*exp(-1i*2*pi*fd_.'*t))*Ts,
but cannot get it to work.
Would welcome any comments/guidance.

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 3 Dez. 2022
Bearbeitet: Bruno Luong am 3 Dez. 2022
Vectorized method but for-loop with preallocation is faster
t = 0:1e-3:1-1e-3;
Ts = 5e-2;
fd_ = -8:0.1:8;
s = rand(size(t));
tic
AF_hat = zeros(length(fd_),2*length(s)-1);
for k = 1:length(fd_)
fd = fd_(k);
AF_hat(k,:) = xcorr(s,s.*exp(-1i*2*pi*fd*t))*Ts;
end
toc
Elapsed time is 0.074924 seconds.
% vectorize way
tic
A_hat2 = conv2(s,flip(conj(s.*exp(-1i*2*pi*fd_(:).*t))*Ts,2));
toc
Elapsed time is 0.083580 seconds.
% Check correctness
norm(AF_hat-A_hat2,Inf)/norm(AF_hat,Inf)
ans = 6.7209e-16
  1 Kommentar
Bruno Luong
Bruno Luong am 6 Dez. 2022
Bearbeitet: Bruno Luong am 6 Dez. 2022
May be faster code since avoid conj and replace flip array by 2 vector-flips
t = 0:1e-3:1-1e-3;
Ts = 5e-2;
fd_ = -8:0.1:8;
s = rand(size(t));
% vectorize way
tic
A_hat2 = conv2(s,(Ts*flip(s)).*exp(2i*pi*fd_(:).*flip(t)));
toc
Elapsed time is 0.076804 seconds.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by