13.1. Fourier For LoopΒΆ

For this assignment, we will both take a sneak peek at using arrays in MATLAB and we will also practice writing a simple for loop.

First, enter the following commands into the MATLAB Command Window. In these lines of code, you can see that the variables t and y are arrays (also called vectors). You can also see that MATLAB has the ability to operate at the array level, which eliminates the need to write a for loop to assign each value of the y array.

>> T = 5;
>> t = 0:15/100:15;
>> y = sin(2*pi*t/T);
>> plot(t,y);

Did you see three cycles of a sine wave?

Next we create a sum of sine waves, which is called a Fourier series. A square wave with a period of T can be expressed with the following Fourier series.

y(t) = \frac{4}{\pi} \sum_{n=1,3,5 \ldots}^{\infty}
    \frac{1}{n} \, \sin( n\,2\,\pi\,t / T)

  1. Create a new script.
  2. Copy the code for creating the variables T and t into the script.
  3. Add the line: y = zeros(1,101);. This lines gives the y array initial values of zero.
  4. Write a for loop where a variable called n has the values of 1, 3, 5, and 7 during the successive iterations of the loop.
  5. In the code block of the for loop enter the Fourier Series sum from above. HINT: Add a new sine term to the existing y array each time through the loop.
  6. After the loop code, multiply y by 4/\pi.
  7. Plot the y array against t. What could you change in your code to make the plot look more like a square wave?
  8. Submit the MATLAB .m file of your script on Canvas.