matlabfft

Using MATLAB to compute fourier coefficients


enter image description here Since I'm freshman of MATLAB, I'm not quite familiar with the functions of MATLAB and I wonder how to compute the fourier coeffiecients of these two periodic functions in MATLAB.

I tried to ask GPT but its code wasn't correct and didn't output the expected answers. I wanna get the correct answers like the attached photo.enter image description here


Solution

  • Check this:

    T=2;dt=0.05;F=1/dt/2;f0=2;
    t=-T-dt:dt:T;
    df=F/length(t);g0=sqrt(dt/F);
    x=cos(2*pi*f0*t);
    f=t/T*F;
    g=g0*abs(fftshift(fft(x)));
    plot(t,x);
    plot(f,g);
    

    Here, t,x is the original signal f,g is the FFT signal, dt=0.05 is the sampling time, F=10 is the Nyquist frequency, T=2 is the total time and f0=2 is the frequency of the cosine.

    Note that f0<F, as you already heard about, which is evident by looking the F range of the frequency plot.

    Note here, that if you change abs by real, the result is the same, since this cosine is perfectly even. Change just one parameter, and you may lost this property.

    Note fftshift is required to do the symmetrical shift magic, which is nothing more than shifting the middle or the array in the beginning.

    Finally, what EVERYBODY MISSES, is the little g0=sqrt(dt/F) factor, which enables both x and g, as calculated before, to satisfy the fabulous Parseval Identity, which means no other thing that the squared integrals of both signals sum(x.^2*dt) and sum(g.^2*df) are the same.

    From here, you finally confirm that the FFT has units of x/t and the Fourier Transform g has units of xt.

    Check the parameters and enjoy yourself from here.

    enter image description here