14.2. 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 can be expressed with the following Fourier series.
See also
Below are instructions to create the Fourier Series of a square wave in MATLAB. Complete the assignment on MATLAB Grader: MATLAB Grader Fourier For Loop Assignment.
- Create a new script.
- Copy the code for creating the variables
T
andt
into the script. - Add the line:
y = zeros(1,101);
. This lines gives they
array initial values of zero. - Write a
for
loop where a variable calledn
has the values of 1, 3, 5, and 7 during the successive iterations of the loop. - In the code block of the
for
loop enter the Fourier Series sum from above. HINT: Add a new sine term to the existingy
array each time through the loop. - After the loop code, multiply
y
by . - Plot the
y
array againstt
. What could you change in your code to make the plot look more like a square wave?