Wednesday, January 3, 2018

matlab - How to calculate Time Delay Estimation?


I have 2 data files, which links are attached below:



Those binary data are read by this MATLAB code:


%% EDIT:


clear all; close all; format long;


%% initial values:
nsamps = inf;
nstart = 0;

Fs = 8e6; % sample rate
flag = 1; % plot in the for loop
c = 3e8; % speed of light

%% input data
file_tx = 'TX.dat';
file_rx = 'RX.dat';
x_tx = readcplx(file_tx, nsamps,nstart);
x_rx = readcplx(file_rx, nsamps,nstart);
data_time = 10; % second % we can set time base on the length of vector x_rx

data_time = floor((length(x_rx) - 8e5)/Fs) * 10;

factor = data_time/10;
matric = reshape(x_rx, [Fs/data_time*factor, data_time + 1]);
matric = matric';
size_of = size(matric);
len = 1:size_of(1);
delay = zeros(1, data_time + 1);

%% time delay calculation:

aa = zeros(1, length(matric(1,:)) - length(x_tx));
signal1 = [x_tx aa];

for i = 1: 1%size_of(1)

signal2 = matric(i,:);
[cc_correlation,lag] = xcorr(signal1, signal2);
[cc_maximum, cc_time] = max(abs(cc_correlation));
cc_estimation = abs(length(signal1) - cc_time);
delay(i) = cc_estimation/Fs; % in second


lagDiff = lag(cc_time);
s2 = signal2(abs(lagDiff)+1:end);
t2 = (0:length(s2)-1)/Fs;
end
%%
fprintf('\n Done! \n\n');

%%%%%%%%%%%%%


function x = readcplx(filename,nsamps,nstart);

fid = fopen(filename);
fseek(fid,4 * nstart,'bof');
y = fread(fid,[2,inf],'short');
fclose(fid);
x = complex(y(1,:),y(2,:));

Answer



Answering the time delay part, use


[corr,lag] = xcorr(tx, rx))

Where tx is one data set and rx is the other. The xcorr function will return the correlation and the index for each correlation as lag (read the help on xcorr for more info).



With that you can find the index of the max value for the correlation and then use that index to look up the lag. This will be the delay in samples, within the precision of your sample rate:


delay = lag(corr==max(corr))

No comments:

Post a Comment

digital communications - Understanding the Matched Filter

I have a question about matched filtering. Does the matched filter maximise the SNR at the moment of decision only? As far as I understand, ...