I know the fundamental frequency of my signal and therefore I also know the other frequencies for the harmonics, I have used the FFT command to compute the first 5 harmonics (for which I know their frequencies). Is it possible for me to find the phase with this available information?
Please note I cant be sure my signal is only one period and therefore need to calculate the phase via the known frequency values.
Code seems to be working:
L = length(te(1,:)); % Length of signal
x = te(1,:);
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(x,NFFT)/L;
f = linspace(1,5,5);
Y(1) = []; % First Value is a sum of all harmonics
figure(1);
bar(f,2*abs(Y(1:5)), 'red')
title('Transmission Error Harmonics')
xlabel('Harmonic')
ylabel('|Y(f)|')
figure(2);
bar(f,(angle(Y(1:5))))
title('Transmission Error Phase')
xlabel('Harminic')
ylabel('Angle (radians)')
Note that if your fundamental frequency is not exactly integer periodic in the fft length, then the resulting phase (atan2(xi,xr)) will be flipping signs between adjacent bins due to the discontinuity between the fft ends (or due to the rectangular window convolution), making phase interpolation interesting. So you may want to re-reference the FFT phase estimation to the center of the data window by doing an fftshift (pre, by shift/rotating elements, or post, by flipping signs in the fft result), making phase interpolation look more reasonable.
In general your Fourier transformed is complex. So if you want to know the phase of a certain frequency you calculate it with tan(ImaginaryPart(Sample)/RealPart(Sample)). This can be done by using angle().
In your case you
1- calculate fft()
2- calculate angle() for all samples of the FFT or for the samples you are interested in (i.e. the sample at your fundamental frequency/harmonic)
EDIT: an example would be
t = [0 0 0 1 0 0 0];
f = fft(t);
phase = angle(f);
phase = angle(f(3)); % If you are interested in the phase of only one frequency
EDIT2: You should not mix up a real valued spectrum [which is basically abs(fft())] with a complex fourier transformed [which is only fft()]. But as you wrote that you calculated the fft yourself I guess you have the 'original' FFT with the complex numbers.
Related
I'm trying to understand how to perform an integration or differentiation of an FFT using MATLAB. However, I think I'm doing something wrong somewhere and would like to know what I'm missing...
Here's an example of an FFT integration that, to the best of my knowledge, should work but doesn't.
clc; clear all; close all;
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sampling period
L = 1500; % Length of signal
t = (0:L-1)*T; % Time vector
f = Fs*(0:(L/2))/L;
omega = 2*pi.*f;
S is the time signal we are going to operate the FFT on, and dS is its derivative. We're going to apply an FFT to dS, and try to integrate that transform to get the same result as S.
S = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
dS = 70*pi*cos(2*pi*50*t) + 140*pi*cos(2*pi*120*t);
P2 = fft(S);
Y = P2(1:L/2+1);
c = fft(dS);
dm = c(1:L/2+1);
From what I found online, to integrate an FFT, you need to multiply each FFT value by the corresponding omega*1i. I'm assuming each point on the FFT result correspond to the values of my frequency vector f.
for z = 1:length(f)
dm(z) = dm(z)./(1i*omega(z));
end
figure
semilogy(f,abs(Y),'b'); hold on
semilogy(f,abs(dm),'r');
We can see on the plot that both curves don't match: the FFT of the initial time signal S is different from the integral of the FFT of the differentiated time signal dS.
The main difference between your two plots is in the noise. Because you use a logarithmic y axis, the noise gets blown up and looks important. Pay attention to the magnitudes when comparing. Anything about 1015 times smaller than the peak value should be ignored. This is the precision of the floating-point numbers used.
The relevant part of these frequency spectra is the two peaks. And the difference there between the sine and cosine is the phase. But you are plotting the magnitude, so the function and its derivative will look the same. Plot the phase also! (but only where the magnitude is above the noise level).
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.
I have generated the following time signal:
Now I want to perform a Discrete Fourier Transform by using the matlab command fft
Here is my code:
function [ xdft, omega ] = FastFourier( t, fs )
%% Inputs from other functions %%
[P_mean, x, u] = MyWay( t ) %From here comes my signal x(t)
%% FFT %%
xdft1 = fft(x); % Perform FFT
xdft2 = abs(xdft1); % Take the absolute value of the fft results
xdft = xdft2(1:length(x)/2+1); % FFT is symmetric, second half is not needed
freq = 0:fs/length(x):fs/2; % frequency axis
plot (freq(1:100),xdft(1:100));
end
And here is the plot that I get:
And what is puzzling to me is the y axis? Shouldn't the y axis represent the amplitudes of the frequency components? Is there a way to get the amplitudes of all the frequency components?
Thanks!
EDIT:
I have found that some people do the following:
n = size(x,2)/2; %The number of components and second half can be neglected again
xdft2 = abs(xdft1)/n;
This way I seem to get the amplitude spectrum, but why do I have to divide the absolute value by n?
FFT gives you a complex pair in each Frequency Bin. The first bin in the FFT is like the DC part of your signal (around 0 Hz), the second bin is Fs / N, where Fs is the sample rate and Nis the windowsize of the FFT, next bin is 2 * Fs / N and so on.
What you calc with the abs() of such a pair is the power contained in a bin.
you might also want to check this out: Understanding Matlab FFT example
Most (not all) FFT libraries preserve total energy (Parseval's theorem), which means that the magnitude has to get bigger for longer FFT windows (longer stationary waveform -> more energy). So you have to divide the result by N to get a more "natural" looking magnitude height of sinewaves in the spectrum.
If you want the amplitudes of the harmonics, then you need to plot real(xdft1) and imag(xdft1). Real(xdft1) gives you coefficients of all the cosine harmonics present in your signal, from -Fs/2 to +Fs/2, (we assume your Fs is large enough to cover all frequencies in the signal) and the imag(xdft) give the amplitudes of the sines.
What you are doing is giving you the magnitude of the signal, which is the RMS value of the total energy at a bin in both the real and imaginary frequency component.
Its often the item of most interest to people looking at a spectrum.
Basics of this: (https://www.youtube.com/watch?v=ZKNzMyS9Z6s&t=1629s)
I'm using Matlab to take FFTs of signals, and I'm getting stuck on the normalization. Specifically, how to normalize the spectrum into units of dBm. I know that 0.316228 is the correct normalization factor, but my questions are related to how to normalize the bins correctly.
I created the following program to raise my questions. Just cut and paste it into Matlab and it'll run itself. See questions in-line.
In particular, I'm confused how to normalize the bins. For example, if the FFT has indices 1:end, where end is even, when I calculate the FFT magnitude spectrum, should I multiply by (2/N) for indices 2:(end/2)? Similarly, does the bin at the Nyquist frequency (located at index end/2+1) get normalized to (1/N)? I know there's a bunch of ways to normalize depending on one's interest. Let's say the signal I'm using (St below) are voltages captured from an ADC.
Any feedback is greatly appreciated. Thanks in advance!
%% 1. Create an Example Signal
N = 2^21 ; % N = number of points in time-domain signal (St)
St = 1 + rand(N,1,'single'); % St = example broadband signal (e.g. random noise)
% take FFT
Sf = fft(St, N);
Sf_mag = (2/N)*abs(Sf(1: N/2 + 1));
Sf_dBm = 20*log10(Sf_mag / 0.316228); % 0.316338 is peak voltage of 1 mW into 50 Ohms
% Q: Are Sf_mag and Sf_dBm normalized correctly? (assume 0.316338 is correct
% peak voltage to get 1mW in 50 Ohms)
% Q: Should Sf_mag(fftpoints/2 + 1) = (1/N)*abs(Sf(fftpoints/2 + 1) for correct normalization
% of Nyquist frequency? (since Nyquist frequency is not folded in frequency
% like the others are)
%% 2. Plot Result
% create FFT spectrum x-axis
samplerate = 20e9; % 20 Gsamples/sec
fft_xaxis = single(0 : 1 : N/2)';
fft_xaxis = fft_xaxis * single(samplerate/N);
semilogx(fft_xaxis, Sf_dBm, 'b-')
xlabel('Frequency (Hz)');
ylabel('FFT Magnitude (dBm)');
title('Spectrum of Signal (Blue) vs Frequency (Hz)');
xlim([1e4 1e10]);
grid on;
I am not totally clear about what you are trying to accomplish, but here are some tips that will let you debug your own program.
Do fft([1 1 1 1]). Do fft([1 1 1 1 1 1 1 1]). In particular, observe the output magnitude. Is it what you expect?
Then do fft([1 -1 1 -1]). Do fft([1 -1 1 -1 1 -1 1 -1]). Repeat for various signal lengths and frequencies. That should allow you to normalize your signals accordingly.
Also, do the same thing for ifft instead of fft. These are good sanity checks for various FFT implementations, because while most implementations may put the 1/N in front of the inverse transform, others may put 1/sqrt(N) in front of both forward and inverse transforms.
See this for an answer:
FFT normalization
Some software packages and references get sloppy on the normalization of the Fourier coefficients.
Assuming a real signal, then the normalization steps are:
1) The power in the frequency domain must equal the power in the time domain.
2) The magnitude of the Fourier coefficients are duplicated (x2) except for DC term and Nyquist term. DC and Nyquist terms appear only once. Depending on how your array indexing starts/stop, you need to be careful. Simply doubling the power to get a one sided spectrum is wrong.
3) To get power density (dBm/Hz) you need to normalize to the individual frequency bin size.
Here is the scenario: using a spectrum analyzer i have the input values and the output values. the number of samples is 32000 and the sampling rate is 2000 samples/sec, and the input is a sine wave of 50 hz, the input is current and the output is pressure in psi.
How do i calculate the frequency response from this data using MATLAB,
using the FFT function in MATLAB.
i was able to generate a sine wave, that gives out the the magnitude and phase angles, here is the code that i used:
%FFT Analysis to calculate the frequency response for the raw data
%The FFT allows you to efficiently estimate component frequencies in data from a discrete set of values sampled at a fixed rate
% Sampling frequency(Hz)
Fs = 2000;
% Time vector of 16 second
t = 0:1/Fs:16-1;
% Create a sine wave of 50 Hz.
x = sin(2*pi*t*50);
% Use next highest power of 2 greater than or equal to length(x) to calculate FFT.
nfft = pow2(nextpow2(length(x)))
% Take fft, padding with zeros so that length(fftx) is equal to nfft
fftx = fft(x,nfft);
% Calculate the number of unique points
NumUniquePts = ceil((nfft+1)/2);
% FFT is symmetric, throw away second half
fftx = fftx(1:NumUniquePts);
% Take the magnitude of fft of x and scale the fft so that it is not a function of the length of x
mx = abs(fftx)/length(x);
% Take the square of the magnitude of fft of x.
mx = mx.^2;
% Since we dropped half the FFT, we multiply mx by 2 to keep the same energy.
% The DC component and Nyquist component, if it exists, are unique and should not be multiplied by 2.
if rem(nfft, 2) % odd nfft excludes Nyquist point
mx(2:end) = mx(2:end)*2;
else
mx(2:end -1) = mx(2:end -1)*2;
end
% This is an evenly spaced frequency vector with NumUniquePts points.
f = (0:NumUniquePts-1)*Fs/nfft;
% Generate the plot, title and labels.
subplot(211),plot(f,mx);
title('Power Spectrum of a 50Hz Sine Wave');
xlabel('Frequency (Hz)');
ylabel('Power');
% returns the phase angles, in radians, for each element of complex array fftx
phase = unwrap(angle(fftx));
PHA = phase*180/pi;
subplot(212),plot(f,PHA),title('frequency response');
xlabel('Frequency (Hz)')
ylabel('Phase (Degrees)')
grid on
i took the frequency response from the phase plot at 90 degree phase angle, is this the right way to calculate the frequency response?
how do i compare this response to the values that is obtained from the analyzer? this is a cross check to see if the analyzer logic makes sense or not.
Looks OK at first glance, but a couple of things you're missing:
you should apply a window function to the time domain data before the FFT, see e.g. http://en.wikipedia.org/wiki/Window_function for windowing in general and http://en.wikipedia.org/wiki/Hann_window for the most commonly used window function (Hann aka Hanning).
you probably want to plot log magnitude in dB rather than just raw magnitude
You should consider looking at the cpsd() function for calculating the Frequency response. The scaling and normalisation for various window functions is handled for you.
the Frequency reponse would then be
G = cpsd (output,input) / cpsd (input,input)
then take the angle() to obtain the phase difference between the input and the output.
Your code snippet does not mention what the input and output data sets are.