i am trying to write a code to cross correlate a transmitted signal with a received signal to determine the number of samples delay - matlab

Cross correlation is to be used to measure distance to an aircraft by transmitting a
known wide-band signal and correlating the transmitted signal with incoming signals
received via the radar reception dish
The transmitted signal x(n) is of length N=512 while the received signal y(n) is of length N=2048.
y(n)=kx(n-d)+w(n); where 'kx(n-d)' is x(n) delayed by d samples and attenuated by a factor k, and w(n) is reception noise.
i am trying to write a MATLAB program to cross correlate x(n) with the y(n) to determine the value of d, the number of samples delay.
And also Determine a suitable sampling frequency if the distance to the aircraft is to be
determined within 50 km to an accuracy of 50 m, given that the transmitted
and received data is travelling at the speed of light.

The easiest way to do this is with the "xcorr" function. This is part of the Signal Processing toolbox for matlab, but should be available for GNU Octave here. I have not checked if the octave script is completely MATLAB compatible.
You can use the xcorr function as:
[correlation,lags] = xcorr(x,y);
The lag value can be found using
delay = lags(find(correlation==max(correlation)))
At the speed of light, the signal will be travelling at 3 x 10^8 m/s, so to have a resolution of 50m, you should be sampling at at least (3e8/50m) = 6MHz. At this sampling rate, each lag will be 1/6000000 second. If you multiply your delay by this value, you get your total time intervel between transmission and reception of the signal. Multiply this time intervel by the speed of light to get your distance.

You can use generalized Cross correlation -Phase transform GCC PHAT
The following is the MATLAB code for it
function time=GCCPHAT_testmode(b1,b2)
b1f=fft(b1);
b2f=fft(b2);
b2fc=conj(b2f);
neuma=(b1f).*(b2fc);
deno=abs((b1f).*(b2fc));
GPHAT=neuma./deno;
GPHATi=ifft(GPHAT);
[maxval ind]= max(GPHATi);
samp=ind
end

we can ignore the 'find' function in matlab, the command could be changed to
delay = lags(correlation==max(correlation))
'xcorr' suits for vectors with long length;
'gcc' prefer frame by frame.

Aj463's comment above is good, indeed GCC-PHAT is better than unweighted correlation for estimating delay of wide-band signals.
I would suggest a small improvement to the code posted above: to add a small value epsilon to the denominator, epsilon -> 0, in order to avoid eventual division by zero.
Thus, I would change the line
deno=abs((b1f).*(b2fc));
to
deno=abs((b1f).*(b2fc)) + epsilon;

Related

Power of Periodic Extension of a Sequence in MATLAB

I have a sequence x[n] that is not zero only for n = [1:3], while it is zero otherwise. I compute its energy as
Ex = sum(abs(x).^2)
and its power as
Px = Ex/length(n)
Now I have a sequence y[n] which is the periodic extension of x[n] with period N = 7. In that case, the energy of y[n] is
Ey = infinity
My question is the following: I compute its power as
Py = Ex/N
I am not sure if I am right about that. It confuses me that I cannot really define this sequence y[n] in Matlab due to its infinite length, as a periodic sequence, but I think I use the right formula.
If someone could give me some response on that, it would be great. Thank you.
Just to be clear, the definition of signal energy and power are given in this slide:
As you can see, signal energy is just the total area under the squared signal, so the formula you used E = sum(abs(x).^2) is correct. Since signals that are periodic will have non-zero values for all time, the energy of a periodic signal is infinite.
However, signal power is defined as the limit of an integral. In the special case of periodic signals, this limit ends up being the area under the average squared signal for one period--in other words, the average energy for one period. In this special case, the formula P = E_period/period_length holds.
If a signal has a finite domain where it is non-zero, the power will be equal to be zero since the integral vanishes in the limit of large T.
The above properties naturally lead to two categories of signals:
energy signals have a finite domain where the signal is nonzero. Therefore, they have finite energy and zero power.
power signals have a finite power and infinite energy. All non-zero periodic signals are power signals.
there is also "third" category of signals that have infinite energy and infinite power. n.^2 is one example.
So to clarify, the power for x[n] is Px = 0 since it is an energy signal, not Px = Ex/length(n) (that's power for periodic signals).
If x[n] is extended periodically forever in both directions, then it has infinite energy and power equal to P = Ex/length_of_period.

how to use ifft function in MATLAB with experimental data

I am trying to use the ifft function in MATLAB on some experimental data, but I don't get the expected results.
I have frequency data of a logarithmic sine sweep excitation, therefore I know the amplitude [g's], the frequency [Hz] and the phase (which is 0 since the point is a piloting point).
I tried to feed it directly to the ifft function, but I get a complex number as a result (and I expected a real result since it is a time signal). I thought the problem could be that the signal is not symmetric, therefore I computed the symmetric part in this way (in a 'for' loop)
x(i) = conj(x(mod(N-i+1,N)+1))
and I added it at the end of the amplitude vector.
new_amp = [amplitude x];
In this way the new amplitude vector is symmetric, but now I also doubled the dimension of that vector and this means I have to double the dimension of the frequency vector also.
Anyway, I fed the new amplitude vector to the ifft but still I don't get the logarithmic sine sweep, although this time the output is real as expected.
To compute the time [s] for the plot I used the following formula:
t = 60*3.33*log10(f/f(1))/(sweep rate)
What am I doing wrong?
Thank you in advance
If you want to create identical time domain signal from specified frequency values you should take into account lots of details. It seems to me very complicated problem and I think it need very strength background on the mathematics behind it.
But I think you may work on some details to get more acceptable result:
1- Time vector should be equally spaced based on sampling from frequency steps and maximum.
t = 0:1/fs:N/fs;
where: *N* is the length of signal in frequency domain, and *fs* is twice the
highest frequency in frequency domain.
2- You should have some sort of logarithmic phases on the frequency bins I think.
3- Your signal in frequency domain must be even to have real signal in time domain.
I hope this could help, even for someone to improve it.

windowed cross correlation in Matlab

i have two signals. one is generated by a phone to a wave file (original signal) and the other signal is recorded to a file (a delayed copy of the first signal).
what i want to do is cross correlate these two signals using MATLAB to know the detection time of that signal and the lag duration. Xcorr inbuilt function correlates at a lag of zero which is not the case here.
i want to know especially how and on what basis i have to set the window length, i read a lot about the correlation but i couldn't really know how start implementing it.
Lets say you have 2 signals of length N and M.The correlation of those 2 signals will have a length (N + M + 1).What windowing does is essentially just crops the signal, but the cropping is from the centre.So if I wanted a window length of K, I would just take the K samples in the middle of the (N + M + 1) length correlated signal.
If for example you cross-correlated two 100-sample long signals and wanted to implement a window length of 160, you would get the cross correlation which would yield a 201 sample long signal and would get the 160 samples in the middle of the cross correlation signal, i.e knock out 20 samples from beginning of the signal and 21 samples from the end of the signal.
Now, lets proceed to delay detection.If I understand you correct you have 2 signals, but one signal is just a delayed version of the other one and you want to estimate what that delay is, is that right?
What you want to do in this case is compute the cross correlation of the 2 signals (with maxlags = 0 ) and find where the cross correlated signal is maximum, the distance between the point where the signal is maximum and the midpoint of cross correlated signal gives you the delay of the signal ( in number of samples, the actual delay in seconds will depend on how many seconds those samples represent ).
Hope I made things clear

Time delay estimation using crosscorrelation

I have two sensors seperated by some distance which receive a signal from a source. The signal in its pure form is a sine wave at a frequency of 17kHz. I want to estimate the TDOA between the two sensors. I am using crosscorrelation and below is my code
x1; % signal as recieved by sensor1
x2; % signal as recieved by sensor2
len = length(x1);
nfft = 2^nextpow2(2*len-1);
X1 = fft(x1);
X2 = fft(x2);
X = X1.*conj(X2);
m = ifft(X);
r = [m(end-len+1) m(1:len)];
[a,i] = max(r);
td = i - length(r)/2;
I am filtering my signals x1 and x2 by removing all frequencies below 17kHz.
I am having two problems with the above code:
1. With the sensors and source at the same place, I am getting different values of 'td' at each time. I am not sure what is wrong. Is it because of the noise? If so can anyone please provide a solution? I have read many papers and went through other questions on stackoverflow so please answer with code along with theory instead of just stating the theory.
2. The value of 'td' is sometimes not matching with the delay as calculated using xcorr. What am i doing wrong? Below is my code for td using xcorr
[xc,lags] = xcorr(x1,x2);
[m,i] = max(xc);
td = lags(i);
One problem you might have is the fact that you only use a single frequency. At f = 17 kHz, and an estimated speed-of-sound v = 340 m/s (I assume you use ultra-sound), the wavelength is lambda = v / f = 2 cm. This means that your length measurement has an unambiguity range of 2 cm (sorry, cannot find a good link, google yourself). This means that you already need to know your distance to better than 2 cm, before you can use the result of your measurement to refine the distance.
Think of it in another way: when taking the cross-correlation between two perfect sines, the result should be a 'comb' of peaks with spacing equal to the wavelength. If they overlap perfectly, and you displace one signal by one wavelength, they still overlap perfectly. This means that you first have to know which of these peaks is the right one, otherwise a different peak can be the highest every time purely by random noise. Did you make a plot of the calculated cross-correlation before trying to blindly find the maximum?
This problem is the same as in interferometry, where it is easy to measure small distance variations with a resolution smaller than a wavelength by measuring phase differences, but you have no idea about the absolute distance, since you do not know the absolute phase.
The solution to this is actually easy: let your source generate more frequencies. Even using (band-limited) white-noise should work without problems when calculating cross-correlations, and it removes the ambiguity problem. You should see the white noise as a collection of sines. The cross-correlation of each of them will generate a comb, but with different spacing. When adding all those combs together, they will add up significantly only in a single point, at the delay you are looking for!
White Noise, Maximum Length Sequency or other non-periodic signals should be used as the test signal for time delay measurement using cross correleation. This is because non-periodic signals have only one cross correlation peak and there will be no ambiguity to determine the time delay. It is possible to use the burst type of periodic signals to do the job, but with degraded SNR. If you have to use a continuous periodic signal as the test signal, then you can only measure a time delay within one period of the periodic test signal. This should explain why, in your case, using lower frequency sine wave as the test signal works while using higher frequency sine wave does not. This is demonstrated in these videos: https://youtu.be/L6YJqhbsuFY, https://youtu.be/7u1nSD0RlwY .

DTMF, DFT window length

We've got an assignment in school to create a DTMF decoder, but are having trouble understanding what needs to be done, and how. First of all we need to calculate the energy of the signal using convolution. We do it by making use of the window length and the absolute value of the input signal:
SmoothEnergyOfInputSignal = conv(abs(X), ones(1,winlen)/winlen); %moving average
Now, we don't know how to get the proper window length. The smoothed energy is used to segment the signal, and later to determine the different frequencies in the signal making use of basis vectors(?)
The dtmf-pulses are at least 40ms separated by at least 40ms of silence.
The sampling frequency is at 8kHz and our signal is about 17601 samples long.
We thought that by doing fs*0.04 we'd get the window length. 0.04=40ms, but now the smoothed energy signal is shifted so the segments go beyond the maximum samples of the input signal.
[Sound, fs] = audioread('dtmf_all.wav');
winlen = fs*0.04
E = conv(abs(Sound),ones(1, winlen)/winlen)
Long story short: How do we calculate the "correct" window length?
Thanks in advance.
EDIT: The instructions were updated, and we're not supposed to use convolution. We're supposed to use filter()