title: How to compute Fourier coefficients with MATLAB
body: <p>I'm trying to compute the Fourier coefficients for a waveform using MATLAB. The coefficients can be computed using the following formulas:</p>
  
  <p><img src="https://i.stack.imgur.com/9KZMe.png" alt="enter image description here"></p>
  
  <p><img src="https://i.stack.imgur.com/WQl2T.png" alt="enter image description here"></p>
  
  <p>T is chosen to be 1 which gives omega = 2pi.</p>
  
  <p>However I'm having issues performing the integrals. The functions are are triangle wave (Which can be generated using <code>sawtooth(t,0.5)</code> if I'm not mistaking) as well as a square wave.</p>
  
  <p>I've tried with the following code (For the triangle wave):</p>
  
  <pre><code>    function [ a0,am,bm ] = test( numTerms )
              b_m = zeros(1,numTerms);
              w=2*pi;
              for i = 1:numTerms
                      f1 = @(t) sawtooth(t,0.5).*cos(i*w*t);
                      f2 = @(t) sawtooth(t,0.5).*sin(i*w*t);
                      am(i) = 2*quad(f1,0,1);
                      bm(i) = 2*quad(f2,0,1);
              end
      end
  </code></pre>
  
  <p>However it's not getting anywhere near the values I need. The b_m coefficients are given for a 
   triangle wave and are supposed to be 1/m^2 and -1/m^2 when m is odd alternating beginning with the positive term.</p>
  
  <p>The major issue for me is that I don't quite understand how integrals work in MATLAB and I'm not sure whether or not the approach I've chosen works.</p>
  
  <p>Edit:
  To clairify, this is the form that I'm looking to write the function on when the coefficients have been determined:</p>
  
  <p><img src="https://i.stack.imgur.com/k14oo.png" alt="enter image description here"></p>
  
  <p>Here's an attempt using fft:</p>
  
  <pre><code>    function [ a0,am,bm ] = test( numTerms )
              T=2*pi;
              w=1;
              t = [0:0.1:2];
              f = fft(sawtooth(t,0.5));
              am = real(f);
              bm = imag(f);
              func = num2str(f(1));
              for i = 1:numTerms
                      func = strcat(func,'+',num2str(am(i)),'*cos(',num2str(i*w),'*t)','+',num2str(bm(i)),'*sin(',num2str(i*w),'*t)');
              end
              y = inline(func);
              plot(t,y(t));
      end
  </code></pre>