User Tools

Site Tools


psyc410_s2x:signal_fft

This is an old revision of the document!


Lab 2 - Signals, Frequency,
and the FFT



Information, Preparation, Resources, Etc.

Readings to be completed prior to this lab:

  • none

Readings to be completed prior to next week's lab:

Based on feedback from students in prior semesters, I suggest you watch/read the videos/readings in the order listed above. However, it's ultimately up to you.

You might feel frustrated and find these readings and videos to be inscrutable at first. That's to be expected. I have deliberately chosen these very short readings (and videos) with the intention that they be read, re-read, and re-re-read. You will read them again after next week's lecture and things will start to come into focus. However, that does not mean you should simply skim them. In order to start to make sense this stuff you need to make a good faith effort to understand it each time you're exposed to it!

Goals for this lab:

  • Get a big-picture understanding of the spectral characteristics of time-series and how the Fourier analysis reveals those characteristics.

Software introduced in this lab

  • none

Housekeeping

  • none

Running Code

Today's lab will use Matlab to understand signals and signal decomposition. The best way to learn MATLAB (indeed, how I learned) is to look at the scripts of other people and read the annotation.

Do NOT simply run the scripts I give you; take the time to understand how they work. I will do my best to thoroughly annotate the scripts so that you can read a description of what the code is doing.

Part 1: Signals and Sine Waves

To understand acquisition and analysis of EEG and fMRI we need to have, at minimum, a basic understanding of sine waves. This is not a trigonometry course so we will not concern ourselves with the math, per se, but it is absolutely essential that you understand waves and wave analysis at least at the conceptual level.

There are plenty of Intro to Trig tutorials online, but I've grabbed a couple from Khan Academy that you might find useful (each are about ~10 minutes long). Watching these is not mandatory nor part of your lab assignment, but I strongly suggest watching them on your own time if the sine wave stuff in this section makes you scratch your head in confusion. Again, performing the math is not necessary, but having a sense of what a sine wave represents is necessary.














A sine wave is a curve with repetitive oscillation of constant amplitude. The sine wave has three properties:

  • frequency (f): how fast the wave goes up and down. Measured in cycles per second, or “hertz” (Hz).
  • amplitude (A): how big (i.e., tall) is the wave. Power is amplitude squared, and so these terms are sometimes used interchangeably.
  • phase (theta): the timing of the sine wave. Measured in radians or degrees.

To better understand each of these properties, see the figures and play with the code in the following section

The frequency of the sine wave is directly related to the period and wavelength.

  • wavelength (lambda): the distance traveled by one cycle
  • period (T): how long it takes to complete one cycle
  • frequency is the reciprocal of the period f = 1/T
  • period is the reciprocal of the frequency T = 1/f

These three properties (frequency, amplitude, phase) describe the sine wave in the following formula.

A sin(2 pi ft + theta)
A is the amplitude of the sine wave
pi is pi, or 3.141…
f is the frequency
t is the time
theta is the phase angle.

Creating A Sine Wave

1. Run the following code to create your first sine wave.

Technically, you're creating a “real-valued sine wave”. But don't fret, we'll create a complex sine wave soon!

To run the MATLAB code:

Option #1

  1. Download the script by clicking on the tab above the code (Note that MATLAB scripts end with a .m file extension)
  2. Open the script in MATLAB
  3. If this is your very first time opening one of the .m scripts in MATLAB you'll need to do the following
    1. 'right-click' on the file and select Get Info
    2. Expand the Open with: section and change Xcode.app to MATLAB_R2024b.app
    3. Press Change All
    4. Confirm
    5. That's it. You should not ever have to repeat these steps. From now on these files should open in MATLAB by default.
  4. Press the Run button (if you do not see the Run button (see below), first select the Editor tab at the top of the window)
  5. If you get a warning that the file is not found in the current folder… select the Add to Path option.

Option #2

  1. Open MATLAB
  2. Select New Script in the upper left corner of your MATLAB window
  3. Copy and paste the code from this wiki into the untitled document in MATLAB
  4. Save the file using the file name displayed in the tab above the code (on the wiki)
  5. Press the Run button (if you do not see the Run button, first select the Editor tab at the top of the window)
  6. If you get a warning that the file is not found in the current folder… select the Add to Path option.

Option #3

  1. Run the code by copy and pasting it directly into the command window
    1. I don't recommend this option because you will not be able to go back and modify anything once it's been run.
lab_2_1.m
% MATLAB code
% Create and plot a sine wave
 
% Define variables
srate = 1000; % sampling rate of 1 kHz
time  = 0:1/srate:2; 
freq  = 2; % in Hz
amp   = 3; % amplitude, or height of the sine wave
angle = 0; % phase angle of wave
theta = angle * (pi / 180); % phase of the sine wave (radians) converted from the angle parameter
 
% Create sine wave
sine_wave = amp.*sin(2*pi*freq.*time+theta); % Note that you need the .* for point-wise vector multiplication.
 
% The following code will plot your sine wave
figure
plot(time,sine_wave)
% set(gca,'ylim',[-4 4]) % this adjusts the y-axis limits for visibility
title('My first sine wave!')

LAB REPORT Part 1 - #1

  • Save your figure and embed it into your lab report with a label/figure caption.
    • On the figure window select File –> Save as
    • Change format from .fig to .jpg
    • The default is to save the file into the MATLAB directory. You should save to the desktop instead so that you don't lose track of your files.

With regard to naming and saving files …. Be consistent! Be organized!

Data analysis (and thus this lab) generally requires creating lots and lots of files, figures, scripts, etc. You will be doing yourself a huge favor to give things descriptive and meaningful titles. By the same token, you should have an organized directory structure in which you put your files. A desktop covered in random files will eventually cause profound sadness. Take the time in advance to think how you want to organize and name things. Future you will be very thankful!

(As you go you might find that you need to update and refine your system. But better to refine an imperfect system than to be lost in avalanche of your own work)

For all lab reports, your figures should be “publication quality”. This means that

  • images should be high quality (reasonably high resolution)
  • text should be legible
  • Images should be cropped, manipulated, etc. to highlight important information and remove/diminish unimportant information.

For tips, see this page

2. Now try running it a few more times. Each time change the freq and/or amp variables to see how it affects your sine wave. It might be most informative to only change parameter one at a time.

LAB REPORT Part 1 - #2

  • Save at least two of your modified sine waves and embed them into your Word document lab report.
  • Label your figures with the new freq and/or amp that you used.
  • Describe how these changes affected your sine waves

Phase Offset

3. To demonstrate how phase angle (theta) affects the sine wave, run the following code which will create two waves offset by 90°. The blue wave has theta = 0° and the red wave has theta = 90°, but the amplitudes and frequencies are the same.

The code requires that the phase be reported in radians (the theta value in the code), but it is often easier to refer to it in “degrees”, as I did in the lecture. Conversion between the two is trivial.
deg=rad*(180/pi) rad=deg*(pi/180)

theta



So I have written this into the code so that you can enter a phase angle (0-360 degrees) for the angle value, and the code will convert that to radians for creation of the sine wave. In the code below, if we wanted a phase angle of 90° we would set angle to 90 and the program would convert that to theta=1.5708.

lab_2_2.m
% MATLAB code
% Plot two sine waves offset by 90°
 
% Define variables in common for both waves
srate = 1000; % sampling rate of 1 kHz
time  = 0:1/srate:2;
 
% Define variables for
% Sine wave 1 
freq  = 2; % in Hz
amp   = 3; % amplitude, or height of the sine wave
angle = 0; % phase angle of the wave
theta = angle * (pi / 180); % phase of the sine wave (radians) converted from the angle parameter
 
sine_wave_1 = amp.*sin(2*pi*freq.*time+theta); % Note that you need the .* for point-wise vector multiplication.
 
% Define variables for
% Sine wave 2 
freq  = 2; % in Hz
amp   = 3; % amplitude, or height of the sine wave
angle = 90; % phase angle of the wave
theta = angle * (pi / 180); % phase of the sine wave (radians) converted from the angle parameter
 
sine_wave_2 = amp.*sin(2*pi*freq.*time+theta); % Note that you need the .* for point-wise vector multiplication.
 
% The following code will plot your sine wave
figure
plot(time,sine_wave_1); hold on
plot(time,sine_wave_2,'r')
% set(gca,'ylim') % this adjusts the y-axis limits for visibility
title('More sine waves!')

3. Plot and save the output of the above code.

4. Before moving on to the next section play around with the amplitude (amp), frequency (freq), and phase angle (angle) values and see what effect they have on your waves. Use different parameters for the two different waves. Save one of these figures.

LAB REPORT Part 1 - #3

  • Embed the original and modified figures into your Word document lab report.
  • Report how your changes to the phase offset affected the relationship between the sine waves

Complex Waves

The waves we've seen so far are “simple” waves because they are perfectly sinusoidal (aka “pure”). That is, the wave is completely described by a single value for each of the three parameters; amplitude, frequency, and phase. A complex wave, on the other hand, is made up of more than one pure sine wave. For example a pure sine wave is created when you press a single key on a piano. The sound waves created are oscillating at only one frequency. However, if you were to play a chord (many keys simultaneously) then the sound wave would be a complex combination of the sine wave generated by each of the keys. The sound waves would be a combination of many frequencies.

The math to calculate this new complex wave is extremely complicated. It requires that you <checks notes> add numbers together. Hmm, okay I guess it's not terribly complicated.

5. Let's re-create the waves we created in the last section, but this time we'll also create a third wave that represents the linear combination of the two (i.e., the sum of adding them together). This complex wave will be plotted in green.

lab_2_3.m
% MATLAB code
% Combine two sine waves
 
% Define general variables
srate = 1000; % sampling rate of 1 kHz
time  = 0:1/srate:2;
 
% Define variables for
% Sine wave 1 
freq  = 2; % in Hz
amp   = 3; % amplitude, or height of the sine wave
angle = 0; % phase angle of wave
theta = angle * (pi / 180); % phase of the sine wave (radians) converted from the angle parameter
 
sine_wave_1 = amp.*sin(2*pi*freq.*time+theta); % Note that you need the .* for point-wise vector multiplication.
 
% Create name for figure legend
name1 = sprintf('f=%0.1f, a=%0.1f, pa=%0.1f',freq,amp,angle);
 
% Define variables for
% Sine wave 2 
freq  = 2; % in Hz
amp   = 3; % amplitude, or height of the sine wave
angle = 90; % phase angle of wave
theta = angle * (pi / 180); % phase of the sine wave (radians) converted from the angle parameter
sine_wave_2 = amp.*sin(2*pi*freq.*time+theta); % Note that you need the .* for point-wise vector multiplication.
 
% Create name for figure legend
name2= sprintf('f=%0.1f, a=%0.1f, pa=%0.1f',freq,amp,angle);
 
% Create Sine wave 3 by simply adding sine_wave_1 and sine_wave_2
sine_wave_3 = sine_wave_1 + sine_wave_2;
 
% Create name for figure legend
name3 = 'combined wave';
 
% The following code will plot your sine wave
figure
plot(time,sine_wave_1); hold on
plot(time,sine_wave_2,'r')
plot(time,sine_wave_3,'g')
legend(name1,name2,name3);
% set(gca,'ylim') % this adjusts the y-axis limits for visibility
title('Complex waves!');

This creates the following figure (without the annotations):

Complex Wave

Note that at any given location along the x-axis, the amplitude of the new wave is equal to the sum of the values found on our original waves at that same location. In the figure above I report the values of the red, blue, and green lines where they intersect .6 on the x-axis. The value on the green line (the combined wave) is the sum of the other two.

This is an important point to consider in the next section.

Constructive and Destructive Interference

6. Given what we've learned, what do you think would happen if we combined two identical waves (same frequency, amplitude, and phase)? To find out, modify and your code from lab1_3.m so that wave 1 and wave 2 are identical.

LAB REPORT Part 1 - #4

  • Save and embed the new figure you've created into your Word document lab report.
  • Report what happens when you combine two sine waves with the same frequency, amplitude, and phase.

The figure you create should have a new (green) wave with the same frequency and phase as the others, but double the amplitude. This is called constructive interference; the superposition (fancy way of saying that the two waves are occupying the same space; this is really just the combination of the two waves, which we now know is simply the point by point sum) is larger than either of the contributing waves.

7.Let's look at another extreme. This time let's see what happens when we combine two waves with equal amplitude and frequency, but a phase offset of 180° (pi). Modify your code from lab1_3.m so that wave1 and wave 2 are 180° out of phase.

LAB REPORT Part 1 - #5

  • Save and embed the new figure you've created into your Word document lab report.
  • Report what happens when you combine two sine waves with the same the same frequency and amplitude, but that are 180° out of phase.

In this case we can see that our two waves cause destructive interference and the superposition is smaller than either of the individual waves. Actually, in this case because the waves are perfectly out of phase with one another (“anti-phase”) the resultant wave is a flat line.

Congratulations! You just learned how to build noise canceling headphones. Okay, not quite. But by identifying unwanted sounds (i.e. sound waves) in the environment and then playing waves that are anti-phase to the unwanted ones … poof you make the unwanted sounds disappear.

The following video further demonstrates the effects of constructive/destructive interference.



So far we've just been combining two different sine waves, but everything we've learned applies just the same regardless of how many waves we're talking about. For instance, I could combine the following five sine waves (frequencies and amplitudes are summarized in the table)

Wave Frequency Amplitude
One 3 5
Two 10 15
Three 5 10
Four 15 5
Five 22 7

Cohen_AnalyzingTimeSeris_Fig11.2a

and I'd get this complex wave.

Cohen_AnalyzingTimeSeris_Fig11.2b

Fourier Transform

What if we wanted to take any given signal and know what simple waves needed to be summed together in order to create it? We would use the "Fourier transform", of course! Joseph Fourier (1768-1830) claimed that any complex signal can be described as the sum of sine waves of varying amplitude and frequency. That is, signals could be decomposed into a set of “basis functions” that, if linearly added, would create the complex wave. This decomposition is called the Fourier transform.

This is sort of like having a great meal at a restaurant, then going home and trying to figure out the recipe. What were the ingredients that the chef used and in what quantities? If you can figure that out and add them back up again, you've got your great meal!

We will not concern ourselves with the math of the Fourier transform, but let's see what kind of results it gives us. To do so, we really just need to look at the signals shown at the end of the last section. Let's say we started with this complex signal and wanted to know what basis functions it was made from.

Cohen_AnalyzingTimeSeris_Fig11.2b

time-domain

Using the Fourier transform to decompose this signal we learn that it is made up of the following simple sine waves, each with their own frequency, amplitude, and phase. We would say that this description is in the time-domain because the complex wave is represented by a series of sine waves that each vary over time.

Cohen_AnalyzingTimeSeris_Fig11.2a

frequency-domain

We can also represent this exact same information in the frequency-domain. That is, we can describe the signal in terms of how much each frequency contributes to the total, which is what's done in the plot below. The x-axis now represents frequency rather than time and the y-axis still represents amplitude. Compare the bar graph to the table at the end of the last section. You'll see that the Fourier analysis has accurately identified which frequencies are present and at what amplitudes.

psyc410_lab1_freqdom

Those of you paying very close attention will have noticed that our frequency-domain representation (the bar graph) is not displaying all of the information in our sine waves. It shows us the frequency and the amplitude but has ignored the phase. That's okay here. The importance of phase and how we represent it are stories fro another time.

time- and frequency- domain equivalence

In summary, these two plots represent the exact same signal. The one on the left represents the signal in the time domain, whereas the one on the right represents the signal in the frequency-domain. But importantly, neither is any more informative than the other. They contain the same information and (theoretically) we can go back and forth between them.

Cohen_AnalyzingTimeSeris_Fig11.2b psyc410_lab1_fft.m

LAB REPORT Part 1 - #6

  • The figure below is the combination of three sine waves with the following frequencies and amplitudes:
    • Wave 1: frequency = 5 Hz, amplitude = 14
    • Wave 2: frequency = 7 Hz, amplitude = 10
    • Wave 3: frequency = 2 Hz, amplitude = 6
  • Use Excel (or any program you'd like) to create a bar graph showing the predicted results of a Fourier analysis.
    • You can even hand draw this if it's easier. But in that case you'll need to scan you're drawing and put it in your Word document.

See here for more help on understanding the Fourier transform.

psyc410_s2x/signal_fft.1737312950.txt.gz · Last modified: 2025/01/19 13:55 by admin

Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International
CC Attribution-Share Alike 4.0 International Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki