Fourier transform of simple sin wave in matrix
I am trying to show the spectrum of a simple sine wave, as we know that one strong wave with a fixed frequency must have a peak in its spectrum. I am writing this code, but I cannot get this one peak, what is wrong in my code:
clc nsteps=200;%number of signal elements in time domain i=sqrt(-1); NFREQS=100;%number of elements in frequency domain ddx=1e-9; dt=ddx/(6e8);%separation between each time domain elements lambdai=150e-9; lambdaf=500e-9; freqi=3e8/lambdai; freqf=3e8/lambdaf; freq=zeros(1,NFREQS); for j=1:NFREQS freq(j)=freqi-j*(freqi-freqf)/NFREQS;%desired frequency domain end arg=2*pi*freq*dt; et=zeros(nsteps,1); for j=1:nsteps et(j)=sin(2*pi*3e15*j*dt);%sin wave in time domain end e=zeros(NFREQS,1); for n=1:NFREQS for j=1:nsteps e(n)=e(n)+et(j)*exp(-i*arg(n)*n);%sin wave in frequency domain end end lambda=linspace(lambdai,lambdaf,NFREQS); plot(lambda,abs(e))
source to share
The key point here is using the window function. The resulting code:
clc clear nsteps=40000; i=sqrt(-1); Sc=0.5; ddx=1e-9; dt=ddx*Sc/(3e8); lambdai=100e-9; lambdaf=700e-9; lambda=lambdai:1e-9:lambdaf; [m,NFREQS]=size(lambda); freq=3e8./lambda; et=zeros(nsteps,1); for j=1:nsteps et(j)=sin(2*pi*3e8/(300e-9)*dt*j);%sin wave in time domain end w=blackman(nsteps);%window function for periodic functions for j=1:nsteps et(j)=et(j)*w(j); end e=zeros(1,NFREQS); for n=1:NFREQS for j=1:nsteps e(n)=e(n)+et(j)*exp(-i*2*pi*freq(n)*dt*j); end end plot(lambda,abs(e))
And the result:
source to share
You can use the built-in Fourier transform that MATLAB provides instead of writing your own. See http://www.mathworks.se/help/techdoc/math/brentm1-1.html
Update
The feature fft
you should be aware of has a few quirks. First, the array it generates must be normalized with a factor 1/N
, where N
is the size of the array (this is due to the implementation of the MATLAB function). If you do not do this, all amplitudes in the frequency domain will be N
times greater than they "actually".
Second, you need to somehow find the frequencies that each element in the output array corresponds to. The third line in the code below converts the array of samples to frequencies that match the array fourier
.
This function takes a signal in the time domain and displays it in the frequency domain. t
is the time array, and y
are the signal amplitudes.
function plotSpectrum(t, y)
freqUnit = 1 / (abs(t(2) - t(1)) * length(t));
f = -length(t) * freqUnit : freqUnit : (length(t) - 1) * freqUnit;
oneSidedFFT = fft(y);
fourier = horzcat(oneSidedFFT, oneSidedFFT);
plot(f, abs(fourier));
xlabel('Frequency');
ylabel('Magnitude');
source to share