how to retrieve original signal from power spectrum - matlab

I have calculated power spectrum of signal. the steps are:
FFT of time signal
square of absolute value of FFT/length of signal i.e power spectrum
Now I want to convert it into time domain. What steps should I follow.

The reconstruction of the original signal from the frequency-domain requires both the magnitude and the phase information. So, as you compute the power spectrum and keep only the magnitude, you no longer have all the required information to uniquely reconstruct the original signal.
In other words, we can find examples where different signals have the exact same power spectrum. In that case retrieving which one of those different signals was the original one would thus not be possible.
As a simple illustration, let's say the original signal x is:
x = [0.862209 0.43418 0.216947544 0.14497645];
For sake of argument, let's consider some other signal y, which I've specially crafted for the purpose of this example as:
y = [-0.252234 -0.0835824 -0.826926341 -0.495571572];
As show in the following plots, those two signals might appear completely unrelated:
They do however share the same power spectrum:
f = [0:N-1]/N;
Xf = fft(x,N);
Yf = fft(y,N);
hold off; plot(f, Xf.*conj(Xf)/N, 'b');
hold on; plot(f, Yf.*conj(Yf)/N, 'r:');
xlabel('Normalized frequency');
legend('Px', 'Py')
title('Power spectrum');
As a result, someone who only sees the power spectrum and doesn't know that you started with x, could very well guess that you instead started with y.
That said, the fact that those signals have the same power spectrum could tell you that those signals aren't as unrelated as you might think. In fact those signals also share the same autocorrelation function in the time-domain:
Rx = xcorr(x);
Ry = xcorr(y);
t = [0:length(Rx)-1] - length(x) + 1;
hold off; stem(t, Rx, 'bo');
hold on; stem(t, Ry, 'rx');
legend('Rxx', 'Ryy');
xlabel('lag');
title('Autocorrelation');
This is to be expected since the autocorrelation can be obtained by computing the inverse transform (with ifft) of the power spectrum. This, however, is about as much as you can recover in the time domain. Any signal with this autocorrelation function would be as good a guess as any for the original signal. If you are very motivated you could attempt to solve the set of non-linear equations that are obtained from the definition of the autocorrelation and obtain a list of possibles signals. That would still not be sufficient to tell which one was the original, and as you noticed when comparing my example x and y, there wouldn't be a whole lot to make of it.

The easiest way to see the non-uniqueness of the power (or amplitude) spectrum for describing the time domain signal is that both white noise and the delta function in the time domain have the same power (or amplitude) spectrum - a constant - in the frequency domain.

Related

Matlab: computing signal to noise ratio (SNR) of two highly correlated time domain signals

I'm working in the space of biosignal acquisition. I made a experiment as detailed below, and am now trying to obtain some results from the data.
I have a text file of a signal in Matlab. I loaded the signal onto a waveform generator, then I recorded the generator output on an oscilloscope.
I imported the recorded signal from the oscilloscope back into Matlab.
The Pearson's correlation coefficient between the original signal and the oscilloscope signal is 0.9958 (obtained using corrcoeff function).
I want to compute the SNR of the oscilloscope signal (what I'm calling my signal plus whatever noise is introduced through the digital-to-analog conversion and visa-versa). I have attached a snippet of the 2 signals for reference.
So my original signal is X and oscilloscope signal is X + N.
I used the snr function to compute SNR as follows.
snr(original, (oscilloscope - original))
The result I got was 20.44 dB.
This seems off to me as I would have thought with such a high correlation, that the SNR should be much higher?
Or is it not appropriate to try and compute SNR in this sort of situation?
All help is appreciated.
Thanks
Edit: Graph of a couple of results vs Sleutheye's simulated relationship
You might be surprised at just how even such moderate SNR can still result in fairly high correlations.
I ran an experiment to illustrate the approximate relation between correlation and signal-to-noise-ratio estimate. Since I did not have your specific EEG signal, I just used a reference constant signal and some white Gaussian noise. Keep in mind that the relationship could be affected by the nature of the signal and noise, but it should give you an idea of what to expect. This simulation can be executed with the following code:
SNR = [10:1:40];
M = 10000;
C = zeros(size(SNR));
for i=1:length(SNR)
x = ones(1,M);
K = sqrt(sum(x.*x)/M)*power(10, -SNR(i)/20);
z = x + K*randn(size(x));
C(i) = xcorr(x,z,0)./sqrt(sum(x.*x)*sum(z.*z));
end
figure(1);
hold off; plot(SNR, C);
corr0 = 0.9958;
hold on; plot([SNR(1) SNR(end)], [corr0 corr0], 'k:');
snr0 = 20.44;
hold on; plot([snr0 snr0], [min(C) max(C)], 'r:');
xlabel('SNR (dB)');
ylabel('Correlation');
The dotted black horizontal line highlights your 0.9958 correlation measurement, and the dotted red vertical line highlights your 20.44 dB SNR result.
I'd say that's a pretty good match!
In fact, for this specific case in my simulation (x = 1; z = x + N(0,σ)) if we denote C(x,z) to be the correlation between x and z, and σ as the noise standard deviation, we can actually show that:
Given a correlation value of 0.9958, this would yield an SNR of 20.79dB, which is consistent with your results.

Matlab not plotting the exact fourier signal

I'm trying to plot a simple signal in fourier domain using Matlab. It's not plotting the correct signal. Here is my code:
clc;
clear all;
close all;
x=1:0.001:10;
f1=sin(2*pi*10*x);
f2=sin(2*pi*15*x);
f3=sin(2*pi*30*x);
f=f1+f2+f3;
plot(2*pi*x,fft(f1));
figure
plot(x,fft(f1));
I've expected a peak at 10 since the frequency is 10. But it is giving a peak at some other point
Here are the two plot images:
This is the image for plot(x,fft(f1))
This is the image for plot(2*pi*x,fft(f1))
It is not showing the peak at 10.I even tried using abs(fft(f1)). No luck :/
Isn't it the correct way to plot signal in fourier domain?
The fft function assumes unit time step. In order to correct for non unit time step you need to define the frequency component based on the nyquist rate. The following code plots the magnitude of the fft with the correct frequency axis.
clc;
clear all;
close all;
x=1:0.001:10;
% ^ this is your sampling time step
f1=sin(2*pi*10*x);
f2=sin(2*pi*15*x);
f3=sin(2*pi*30*x);
% bounds of fourier transform based on sampling rate
Fs = 1/0.001;
ff = linspace(-Fs/2,Fs/2,numel(x));
F1 = fftshift(fft(f1)/numel(x));
F2 = fftshift(fft(f2)/numel(x));
F3 = fftshift(fft(f3)/numel(x));
figure();
plot(ff,abs(F1),'-r'); hold on;
plot(ff,abs(F2),'-b');
plot(ff,abs(F3),'-k');
Edit: To answer OPs question in the comment.
Speaking in normalized frequency units (assuming sampling rate of 1). The fft function returns the frequency response from 0 to 2*pi radians, but due to some signal processing properties and the way that discrete signals are interpreted when performing an FFT, the signal is actually periodic so the pi to 2*pi section is identical to the -pi to 0 section. To display the plot with the DC component (0 frequency) in the center we use fftshift which does a circular shift equal to 1/2 the length of the signal on the data returned by fft. Before you take the ifft make sure you use ifftshift to put it back in the right place.
Edit2: The normalization term (/numel(x)) is necessary to estimate the continuous time fourier transform using the discrete fourier transform. I don't remember the precise mathematical reason off the top of my head but the examples in the MATLAB documentation also imply the necessity of this normalization.
Edit 3: The original link that I had is down. I may come back to add a more detailed answer but in the mean time I definitely recommend that anyone interested in understanding the relationship between the fundamentals of the FS, FT, DTFT, and DFT watch Professor Oppenheim's hilariously old, but amazingly informative and straightforward lectures on MIT OpenCourseWare.

How to find the period of a periodic function using FFT?

Assume I have a smooth function (represented as a vector):
x=0:0.1:1000;
y=sin(2*x);
and I want to find its periodicity - pi (or even its frequency -2 ) .
I have tried the following:
nfft=1024;
Y=fft(y,nfft);
Y=abs(Y(1:nfft/2));
plot(Y);
but obviously it doesn't work (the plot does not give me a peak at "2" ).
Will you please help me find a way to find the value "2"?
Thanks in advance
You have several issues here:
You are computing the fft of x when your actual signal is y
x should be in radians
You need to define a sampling rate and use that to determine the frequency values along the x axis
So once we correct all of these things, we get:
samplingRate = 1000; % Samples per period
nPeriods = 10;
nSamples = samplingRate * nPeriods;
x = linspace(0, 2*pi*nPeriods, nSamples);
y = sin(2*x);
F = fft(y);
amplitude = abs(F / nSamples);
f = samplingRate / nSamples*[0:(nSamples/2-1),-nSamples/2:-1];
plot(f, amplitude)
In general, you can't use an FFT alone to find the period of a periodic signal. That's because an FFT does sinusoidal basis decomposition (or basis transform), and lots of non-sinusoidal waveforms (signals that look absolutely nothing like a sinewave or single sinusoidal basis vector) can be repeated to form a periodic function, waveform, or signal. Thus, it's quite possible for the frequency of a periodic function or waveform to not show up at all in an FFT result (it's called the missing fundamental problem).
Only in the case of a close or near sinusoidal signal will an FFT reliably report the reciprocal of the period of that periodic function.
There are lots of pitch detection/estimation algorithms. You can use an FFT as a sub-component of some composite methods, including cepstrums or cepstral analysis, and Harmonic Product Spectrum pitch detection methods.

FFT Plot of an Audio Signal - MATLAB

I'm using MATLAB to plot a recorded sound using the FFT. I want to take the log of the y-axis but I don't know what I did if correct.
Currently, my FFT plotting code looks like this:
nf=1024; %number of point in DTFT
Y = fft(y,nf);
f = fs/2*linspace(0,1,nf/2+1);
plot(f,abs(Y(1:nf/2+1)));
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
What I did is: plot(f,log(Y(1:nf/2+1)));. I replaced abs with log. Is this correct?
Applying log on the coefficients itself doesn't make any sense... especially since the spectra will be complex-valued in nature. However, some people usually apply the log on the magnitude of the spectra (hence the abs call) mostly for visualization purposes so that large values of the magnitude don't overwhelm the smaller values. Applying log in this case will allow the larger values to taper off and the spectrum can be visualized easier. but applying the straight log in my opinion isn't correct. The code you have provided plots the magnitude of the single-sided spectrum and so there's no need to change anything.
If you provided more insight as to why you want to use the log, that would be helpful but right now, I would say that the straight log is incorrect. However, if you really must use the log, apply it on the magnitude instead. Also, to prevent undefined behaviour, make sure you add 1 to the magnitude before applying the log so that zero values of your magnitude get mapped to zero, rather than undefined.
As such, do this instead:
nf=1024; %number of point in DTFT
Y = fft(y,nf);
f = fs/2*linspace(0,1,nf/2+1);
plot(f,log(1 + abs(Y(1:nf/2+1)))); %// Change
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')

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.