Matlab fft on one period of sinewave returns phase of -pi/2. Why? - matlab

While trying to understand Fast Fourier Transform I encountered a problem with the phase. I have broken it down to the simple code below. Calculating one period of a 50Hz sinewave, and applying an fft algorithm:
fs = 1600;
dt = 1/fs;
L = 32;
t=(0:L-1)*dt;
signal = sin(t/0.02*2*pi);
Y = fft(signal);
myAmplitude = abs(Y)/L *2 ;
myAngle = angle(Y);
Amplitude_at_50Hz = myAmplitude(2);
Phase_at_50Hz = myAngle(2);
While the amplitude is ok, I don't understand the phase result. Why do I get -pi/2 ? As there is only one pure sinewave, I expected the phase to be 0. Either my math is wrong, or my use of Matlab, or both of them... (A homemade fft gives me the same result. So I guess I am stumbling over my math.)
There is a similar post here: MATLAB FFT Phase plot. However, the suggested 'unwrap' command doesn't solve my problem.
Thanks and best regards,
DanK

The default waveform for an FFT phase angle of zero is a cosine wave which starts and ends in the FFT window at 1.0 (not a sinewave which starts and ends in the FFT window at 0.0, or at its zero crossings.) This is because the common nomenclature is to call the cosine function components of the FFT basis vectors (the complex exponentials) the "real" components. The sine function basis components are called "imaginary", and thus infer a non-zero complex phase.

That is what it should be. If you used cosine, you would have found a phase of zero.
Ignoring numerical Fourier transforms for a moment and taking a good old Fourier transform of sin(x), which I am too lazy to walk through, we get a pair of purely imaginary deltas.
As for an intuitive reason, recall that a discrete Fourier transform is averaging a bunch of points along a curve in the complex plane while turning at the angular frequency of the bin you're computing and using the amplitude corresponding to the sample. If you sample a sine curve while turning at its own frequency, the shape you get is a circle centered on the imaginary axis (see below). The average of that is of course going to be right on the imaginary axis.
Plot made with wolfram alpha.

Fourier transform of a sine function such as A*sin((2*pi*f)*t) where f is the frequency will yield 2 impulses of magnitude A/2 in the frequency domain at +f and -f where the associated phases are -pi/2 and pi/2 respectively.
You can take a look at its proof here:
http://mathworld.wolfram.com/FourierTransformSine.html
So the code is working fine.

Related

Plotting with a wrong amplitude in MATLAB

I am trying to plot an amplitude spectrum of a signal.
Here is the code:
%My signal: y = 0.001*cos(0.005*pi*t+pi/4);
A = 0.001;
T = 400;
f = 0.0025;
pi = 3.14;
syms m
m=-1:1;
wm=(1/T)*(int((0.001*cos(0.005*pi*t + pi/4))*exp(-j*m*0.005*pi*t),t,0,T));
ww=double(wm);
Amp=abs(ww);
fi=angle(ww);
w=m*2*pi/T;
f=w/(2*pi);
figure('Name','Amplitude spectrum');
stem(f,Amp,'linewidth',2,'color','r'),grid on;
title('Amplitude spectrum'), xlabel('?[rad/s]'), ylabel('|wm|');
But it's plotted with a wrong amplitude. 5x10^-4 instead of 5x10^-3.
Where did I do the mistake?
The magnitude of your plot is correct.
The magnitudes of the impulses located at the fundamental frequency come from the scale of the cosine wave and get divided by 2: 0.001 / 2 = 5e-4. This is because the cos function can be expressed using Euler's formula such that it is a combination of two complex exponentials that are both scaled by half.
Source: Wikipedia
As such, the Fourier Transform of a complex exponential at the desired frequency is a unit-length impulse (i.e. the magnitude is 1). The cosine wave can be expressed as two complex exponentials centered at the positive and negative versions of the fundamental frequency. We further scale by 1/2 due to Euler's formula and with the property of linearity for the Fourier Transform, the impulses additionally get scaled by 1/2. You further have an additional scaling factor for your cosine wave, which scales the impulses yet again. The combination of scales: (1)(1/2)(0.001) thus gives 5e-4.
There's nothing wrong with that output. Also, your scale should be in Hertz, not rad/s. This is because of the formulation of your exponential has pi in it.
I can understand why you'd want to use the symbolic toobox here, but I highly recommend using fft instead. There's no need to get a slow symbolic calculator to compute the frequency representation of a signal when the fft is a faster algorithm to do so. If you are doing this purely to verify what the theoretical magnitude response is for your signal, then that's fine but do not do this when calculating the frequency response in practice.

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 produce a log scale FFT with MatLab

It's my first time performing an FFT within MatLab by experimenting with some example code from the MathWorks website. I was wondering if it was possible to take the code I have and transform the x axis to a log-scale representation rather than linear. I understand most of the code, but it is the x axis line of code that I'm still not 100% sure exactly what it is doing apart from the +1 at the end of the line, which is that fact that MatLab's indexing structure doesn't start on 0.
My code so far is:
[y,fs] = wavread('Wav/800Hz_2sec.wav');
NFFT = 4096;
Y = fft(y,NFFT)/length(y);
f = fs/2*linspace(0,1,NFFT/2+1);
plot(f,2*abs(Y(1:NFFT/2+1))
frequency usually comes out in linear scale from Discrete Fourier Transform. if you want, you can make a new frequency vector in log scale and interpolate the results you already have
fnew=fs/2.*logspace(log10(fs/length(y)),0,npts);
Ynew= interp1(f,Y(1:NFFT/2+1),fnew);
where npts is the length of your new frequency vector. for just plotting
loglog(f,2*abs(Y(1:NFFT/2+1));
honestly IMO, the interpolation thing doesn't work very well because FFT of real signals produces strong peaks and troughs in spectra, so unless you smooth your spectrum first, the interpolated spectrum won't look as nice

How to compute the CTFT using matlab?

I'm trying to find a factor using matlab that requires me to compute the Fourier transform of an input signal. The problem was stated to me this way:
fbin = 50HZ
0 <= n <= 1999
alpha = F {Blackman[2000] . cos[-2pi . fbin . n/2000]} (f)
where F is the Continous Time Fourier Transform operator.
My matlab code looks like this:
blackman_v = blackman(2000);
signal_x = cos(-2 * pi() .* fbin * (0:(1999)) ./ 2000) .* blackman_v';
fft_real = abs(fft(signal_x, 2000));
alpha = fft_real(51); %51 is the bin for 50hz => or {(f * N/Fs)+1}==51
My problem is that I'm supposed to get a value of around 412 for 49hz but I get about 250 (I'm actually verifying some previous results). Did I wrongly translate the problem? I've been battling for quite a while and I really don't see anything wrong here. Thought the value a 50Hz (430) is ok.
Would really appreciate any hint!
EDIT
blackman_v = blackman(2000);
signal_x = cos(-2 * pi() .* fbin * (0:(1999)) ./ 2000) .* blackman_v';
alpha = abs(freqz(signal_x , 1, 2*pi*50/10000))
Do you know what the freqz is? I read matlab doc and it is still not to clear in my head.
Maybe I misinterpreted your question but Matlab is not for continuous time analysis. It's for numerical analysis only, with discrete values. You can however calculate the discrete time fourier transform (DFT) of your signal, the resolution of which will depend on the length of your signal. Are you using a Blackmann window because your signal is non-periodic?
How to calculate the FFT (DFT) in Matlab: http://www.mathworks.se/help/matlab/ref/fft.html
Any discrete Fourier transform will assume that your signal is periodic. If it isn't you will obtain spectral leakage where certain frequency peaks "leak" their energy to the sides resulting in less defined peak with smeared out frequency values. Thus, the time-domain signal is preferably made periodic before calculting the DFT - periodic to the extent that a general pattern is repeated, values does not have to exact between periods since noise can/will be inherent in the signal. Applying a window function to the time-domain signal before calculating the DFT will make the signal periodic but you will have change amplitude values and introduced a low frequency component.

Complex FFT then Inverse FFT MATLAB

I am using the FFT function in Matlab in an attempt to analyze the output of a Travelling Wave Laser Model.
The of the model is in the time domain in the form (real, imaginary), with the idea being to apply the FFT to the complex output, to obtain phase and amplitude information in the frequency domain:
%load time_domain field data
data = load('fft_data.asc');
% Calc total energy in the time domain
N = size(data,1);
dt = data(2,1) - data (1,1);
field_td = complex (data(:,4), data(:,5));
wavelength = 1550e-9;
df = 1/N/dt;
frequency = (1:N)*df;
dl = wavelength^2/3e8/N/dt;
lambda = -(1:N)*dl +wavelength + N*dl/2;
%Calc FFT
FT = fft(field_td);
FT = fftshift(FT);
counter=1;
phase=angle(FT);
amptry=abs(FT);
unwraptry=unwrap(phase);
Following the unwrapping, a best fit was applied to the phase in the region of interest, and then subtracted from the phase itself in an attempt to remove wavelength dependence of phase in the region of interest.
for i=1:N % correct phase and produce new IFFT input
bestfit(i)=1.679*(10^10)*lambda(i)-26160;
correctedphase(i)=unwraptry(i)-bestfit(i);
ReverseFFTinput(i)= complex(amptry(i)*cos(correctedphase(i)),amptry(i)*sin(correctedphase(i)));
end
Having performed the best fit manually, I now have the Inverse FFT input as shown above.
pleasework=ifft(ReverseFFTinput);
from which I can now extract the phase and amplitude information in the time domain:
newphasetime=angle(pleasework);
newamplitude=abs(pleasework);
However, although the output for the phase is greatly different compared to the input in the time domain
the amplitude of the corrected data seems to have varied little (if at all!),
despite the scaling of the phase. Physically speaking this does not seem correct, as my understanding is that removing wavelength dependence of phase should 'compress' the pulsed input i.e shorten pulse width but heighten peak.
My main question is whether I have failed to use the inverse FFT correctly, or the forward FFT or both, or is this something like a windowing or normalization issue?
Sorry for the long winded question! And thanks in advance.
You're actually seeing two effects.
First the expected one goes. You're talking about "removing wavelength dependence of phase". If you did exactly that - zeroed out the phase completely - you would actually get a slightly compressed peak.
What you actually do is that you add a linear function to the phase. This does not compress anything; it is a well-known transformation that is equivalent to shifting the peaks in time domain. Just a textbook property of the Fourier transform.
Then goes the unintended one. You convert the spectrum obtained with fft with fftshift for better display. Thus before using ifft to convert it back you need to apply ifftshift first. As you don't, the spectrum is effectively shifted in frequency domain. This results in your time domain phase being added a linear function of time, so the difference between the adjacent points which used to be near zero is now about pi.