Fourier transform of simple sin wave in matlab

戏子无情 提交于 2019-12-06 00:15:29

You could consider using 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

There are a few peculiar things about the fft function you should know about. The first thing is that the array that it generates needs to be normalized by a factor of 1/N where N is the size of the array (this is because of the implementation of the MATLAB function). If you don't do that all the amplitudes in frequency domain will be N times larger than they "actually" are.

The second thing is that 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 sample times to the frequencies that the fourier array corresponds to.

This function takes a signal in time domain and plots it in frequency domain. t is the time array and y is 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');

The key point in here is using window function. The resulted code is this:

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 is:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!