IntroductiontoMATLAB PDF
IntroductiontoMATLAB PDF
c JONATHAN A. KEMP 2012
Contents
Introduction 2
1. The Basics: MATLAB as a calculator 3
1.1. Example: Using the speed of sound 4
Exercises 1 4
1.2. Brackets 4
1.3. Using sqrt, the built in function for square roots 5
2. Storing numbers: Variables 6
3. Script files 7
3.1. Files and folders (or directories) 8
3.2. Semicolons to prevent printing results on the screen 9
3.3. Commenting code 9
4. Using sin, cos and tan, the built in functions for trigonometry 10
4.1. Example: Diffraction for stereo loudspeakers 10
Exercises 4 11
5. Vectors 11
5.1. Guitar string fundamental mode shape 12
5.2. Using the colon character for specifying ranges within vectors 12
6. Mode shapes for guitar string harmonics 14
Exercises 5 14
E-mail address: [email protected].
Date: August 28, 2012.
1
2 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
Introduction
MATLAB is a computer program that lets you calculate things in a way that
is very intuitive. You can use it as a simple calculator, but the best thing about
MATLAB is the fact that you can start without knowing any computer program-
ming techniques and in no time you will be writing programs to do numerical
computation. All computer-programming languages involve learning some fiddly
commands, but MATLAB keeps this to the absolute minimum, meaning that you
have more time for trying out different ideas.
While MATLAB is a commercial piece of software, Octave is a free competitor
featuring much of the same functionality. In this work the commands described
can be applied successfully in both MATLAB and Octave. If you download and
install Octave, just pretend the word MATLAB is replaced with Octave for the
remainder of the work unless you are told otherwise.
Why is everything not written in MATLAB? The simple answer is that more
traditional programming languages, such as C, C++, Java and so on may be
optimized to run complicated tasks faster once a program has been written. If you
are beginning a project and want to maximize the time spent doing things that
get you results that can be put into a report, though, then MATLAB is for you.
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 3
This work assumes a basic working knowledge of high school mathematics but
nothing more and acts as an introduction to computer programming by illustrat-
ing how it could be used to create results for a project report. In particular, the
field of Musical Acoustics is used as an example wherever possible. This area has
the advantages of being scientifically interesting and relatively cheap to run ex-
periments in. Computer programming, mathematics and music (as well as physics
and digital signal processing) are all topics that will seem more accessible through
working through this booklet.
>>3 * 2
ans = 6
>> 28/4
ans = 7
>>2^3
ans = 8
4 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
1.3. Using sqrt, the built in function for square roots . MATLAB features
a large number of built in functions. Our first example of a function is called sqrt
and calculates the square root of a number. As an example try the following:
>> sqrt(9)
ans = 3
Note that we have to put in the brackets around the number that we are taking
the square root of and sqrt 9 without the brackets gives an error message.
Square roots can be used where we have to work out distances involving mea-
surements taken at right angles using Pythagorus Theorem. For instance, if a
choir is standing in a rectangular grid of four rows, each of 6 singers, how long
does sound take to travel between the the furthest away choir members? Lets
assume that the singers are separated by 70 cm from nearest neighbours in both
the sideways and forwards directions. The distances along the along the rows and
front to back can be worked out in meters using:
>> 4*0.7
ans = 2.8000
>> 6*0.7
ans = 4.2000
giving 2.8 m and 4.2 m respectively. We apply Pythagorus Theorem to give the
distance between furthest performers as:
sqrt(2.8^2 + 4.2^2)
ans = 5.0478
so rough 5.05 m. In order to calculate the time taken we have to take this number
and divide it by the speed of sound as in equation (1). Rather than typing out
the answer again, we can type ans in its place to give:
>> ans/340
ans = 0.0148
So the sound takes just less than 0.015 s or 15 milliseconds to travel between
the furthest members of the choir. Musical ensembles of this size and bigger will
6 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
usually have a conductor beating time and part of the reason is to prevent timing
differences between performers becoming noticeable.
>> who
Your variables are:
ans c d t
>> clear
>> who
After the clear command has been entered there are no variables left and the who
command doesnt return us any text.
3. Script files
So far we have entered MATLAB commands one at a time using the command
line. MATLAB can also run commands stored in separate files called script files.
These files contain the text for the commands you wish to run and should be saved
with a name ending in .m (for instance myscript.m).
If you are using MATLAB then we can begin writing a script file simply by
typing edit and pressing return (dont include the quotation marks). This makes
MATLABs built in text editor pop up. In Octave it may be necessary to use open
a separate text editing program (many free ones are available).
After opening the editor, enter the commands:
clear
c = 340
d = sqrt(2.8^2 + 4.2^2)
t = d/c
into a new empty text document and save the file, with file being named myscript.m
(again, dont include the quotation marks). Note that it is helpful to make your
file names quite specific so that they dont clash with an existing functions built
in to MATLAB (i.e. dont name it sqrt.m).
Now go back to the command line and type ls (which is short for list the con-
tents of the current folder). If you have saved the file myscript.m in the appropriate
place then the output should be:
>> ls
myscript.m
Type myscript into the command line (making sure you dont include the
quotation marks or the .m on the end of the file name). The command line
should then read:
>> myscript
c = 340
d = 5.0478
t = 0.0148
If you achieve this then well done, you have successfully run your first script file.
Note that the command line output doesnt show the sqrt command that was
used to compute the value of d, just the numerical result.
8 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
3.1. Files and folders (or directories). If there has been a problem running a
script file because you are not in the correct folder or the file name is wrong then
you will see an error message along the lines of:
>> myscript
??? Undefined function or variable myscript.
if you are using MATLAB or
octave-3.2.3:10> myscript
error: myscript undefined near line 10 column 1
if you are using Octave. Type pwd then enter and we should see something
along the lines of:
>> pwd
ans = /Users/Jonathan/Documents/MATLAB
for the user called Jonathan on a Mac OS X computer, but the answer will of
course depend on you and your system. The way to remember the command
pwd is by remembering the acronym Present Working Directory where the
word directory just means folder. If, on the other hand, we know that we
have stored the myscript.m file in /Users/Jonathan/Documents/MATLAB and
the pwd command actually returns:
>> pwd
ans = /Users/Jonathan
then we know we need to change folders. This can be done using the cd command
(where cd stands for change directory) as follows:
>> pwd
ans = /Users/Jonathan
>> cd Documents/MATLAB
>> pwd
ans = /Users/Jonathan/Documents/MATLAB
or you can specify the full name of the folders. On a Windows computer this may
be done with something along the lines of:
>> cd C:/Users/Jonathan/Documents/MATLAB
ans = C:/Users/Jonathan/Documents/MATLAB
where the C: is used by Windows as the drive letter for the hard drive used
to store the data.
If you need to get out of a folder we can type cd .. and press enter (which is
known as changing directory to go into the parent directory) and if you want to
go back to the directory that you started with just type cd and press enter (this
is known as going to the home directory). If, on the other hand you are not sure
where you saved the file myscript.m then go back to the editor and try selecting
Save As... from the File menu. The main thing is that typing myscript into
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 9
the command line should work if the file myscript.m is in the present working
directory.
3.3. Commenting code. The text in a script file is a form of computer code
and well written code should be easy to read and as easy to understand as is
possible. It certainly helps if you make sensible variable names, but an essential
part of making your code easy to understand is including comments that are
actually ignored by the computer when the code runs but which explain in words
what the other lines are for. In MATLAB anything written to the right hand side
of a percentage sign % is ignored by the computer when the script is run. For
instance try changing the contents of myscript.m to read:
%Clear all variables that have been stored before:
clear
%Store the speed of sound (measured in m/s) in a variable called c:
c = 340;
%Calculate the distance in meters using Pythagoruss Theorem and
%store this in a variable called d:
d = sqrt(2.8^2 + 4.2^2);
%Calculate the time taken for sound to travel distance d and store
%this in a variable called t and display the results on the screen:
t = d/c
Typing myscript into the command line will now give exactly the same answer:
>> myscript
t = 0.0148
but the code is now much easier for anyone to interpret.
10 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
4. Using sin, cos and tan, the built in functions for trigonometry
Trigonometry in MATLAB is done by typing sin, cos or tan as appropriate
followed by angle values contained by a pair of brackets. The calculations are
all performed assuming radians (rather than degrees) so that a full rotation is 2
radians. In MATLAB we can also access the value of simply by typing pi.Try
the following examples:
>> sin(0)
ans = 0
>> sin(pi/4)
ans = 0.7071
>> sin(pi/2)
ans = 1
>> cos(0)
ans = 1
>> cos(pi/2)
ans = 6.1232e-17
>> cos(pi)
ans = -1
>> tan(pi/4)
ans = 1.0000
Note in particular that the exact answer for cos(/2) is zero. Why then is MAT-
LAB showing a value other than zero? The answer is that MATLAB is designed
to do calculations numerically. There is a finite number of decimal points in the
approximation of the value of and a finite number of accurate decimal points
in calculating the cosine function. The value of 6.1232e-17 (or 6.1232 1017 )
corresponds to the typical accuracy that MATLAB is working to. If MATLAB
was prioritised to do symbolic computations instead of numerical computations
then it could get the exact answer, but in practice tiny rounding errors like this
are seldom a problem.
4.1. Example: Diffraction for stereo loudspeakers. As an example of using
trigonometric calculations inside a script, consider two loudspeakers in a stereo
system are separated by a distance of L. Lets assume that a listener very far away
from these speakers (in comparison to the distance between the two speakers) and
is off to one side so that the sound from the speakers arrives out of phase. The
distance between the listener and the two speakers will have a length difference of:
(2) d = L sin()
where is the angular position of the listener (in radians) with respect to the
line of equal distance from the speakers (which is perpendicular to a line drawn
between the speakers). Create a script, starting with the clear command, followed
by definitions of the variables for the distance between the source (in metres) of
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 11
d = 1.1 and an angular position of listener (in radians) of = pi/4 as well as the
speed of sound (in m/s) of c = 340 to calculate the difference in the time taken
for sound to travel from the two loudspeakers to a distant listener.
Creating a script for this involves both equations (1) and (2), for example:
%Clear any old variables (in case we use them by accident):
clear
%Speed of sound
c = 340;
%Anglular position (radians) of listener from line
%of equal distance from speakers:
theta = pi/4;
%Distance between speakers (metres):
L = 1.1;
%Calculate difference in distance travelled (metres):
d = L*sin(theta);
%Time difference (seconds) calculated using difference in distance:
t = d/c
Exercises 4. 4.1). Create a MATLAB script which calculates the distance be-
tween the loudspeakers if a distant listener is at an angular position of = /8
and the time difference between the loudspeakers is t = 1 millisecond.
5. Vectors
We have seen how variables are powerful containers for numerical values MAT-
LAB. Experimental data, however, often comes in the form of lists of values,
whether these are data points for a graph or a sampled sound wave. In order to
store such information in MATLAB we need to use vectors. We can define a vector
in MATLAB using square brackets and commas. As an example, lets manually
type in a vector consisting of a ramp of values from 0 to 1 in steps of 0.1 and store
it as x as follows:
>> x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
x =
Columns 1 through 7
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000
Columns 8 through 11
0.7000 0.8000 0.9000 1.0000
We can then use the letter x access any of the values stored in the vector using
ordinary brackets as follows:
>> x(1)
ans = 0
>> x(2)
ans = 0.1000
12 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
>> x(7)
ans = 0.6000
>> x(11)
ans = 1
Note that we are referring to the first entry in x as entry number 1 and this has a
value of 0.
5.1. Guitar string fundamental mode shape. The simplest form of vibration
for a guitar string has a standing wave shape consisting of half a period of a sine
wave. This is known as the fundamental mode of vibration for the string and the
shape can be approximated using:
(3) y = sin(x)
where x is a vector with values between 0 to 1. We will plot the shape of this
vibration as follows:
>> y = sin(pi*x)
y =
Columns 1 through 7
0 0.3090 0.5878 0.8090 0.9511 1.0000 0.9511
Columns 8 through 11
0.8090 0.5878 0.3090 0.0000
>> plot(x,y)
I have assumed here that we still have the vector for x created in the previous
section and if this has been done correctly a plot showing an arch should have
popped up in the screen. Most functions in MATLAB will return a vector y with
the same size as the input x and sin does indeed behave in this way. The arch
will have a slightly rough appearance due to the fact that there are only 11 data
points used.
5.2. Using the colon character for specifying ranges within vectors. The
plot we produced in section 5.1 would be smoother, and more accurate, if we use
a larger number of data points. It would be tedious to make a vector containing,
say, 100 terms by manual typing. Instead we want to use the colon character :
to do the job of creating a vector of an arithmetic series for us. Try typing the
following:
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
This is an example of how the notation a:b creates a vector going from a to b in
steps of 1. If we include an extra colon character then we can specify the step size
for a more general arithmetic series. Try the following:
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 13
>> 1:2:10
ans =
1 3 5 7 9
We have specified a starting point of 1, a step size of 2 and the range and a
maximum value of 10. The last value in the vector is actually 9 because 11 would
the next value in the series and this would exceed the maximum value.
If we want to create the vector x defined in section 5 using this notation it could
be done by specifying a starting value of 0, a step size of 0.1 and a maximum value
of 1 as follows:
>> x = 0:0.1:1
x =
Columns 1 through 7
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000
Columns 8 through 11
0.7000 0.8000 0.9000 1.0000
To increase the number of points in the range, or resolution, we could specify a
smaller step size, say of a hundredth instead of a tenth. This is done in the next
line, with a semicolon character at the end of the line so that the long vector isnt
shown on the screen:
>> x = 0:0.01:1;
Now if we type in the following to recreate the plot from section 5.1, but with
better resolution:
>> y = sin(pi*x);
>> plot(x,y)
Another use of the colon character is to look at a range within a vector. Say we
wish to show the first 6 values in x and y, this can be achieved using:
>> x(1:6)
ans =
0 0.0100 0.0200 0.0300 0.0400 0.0500
>> y(1:6)
ans =
0 0.0314 0.0628 0.0941 0.1253 0.1564
It is interesting to note that the first values in y = sin(x) are approximately equal
to x:
>> pi*x(1:6)
ans =
0 0.0314 0.0628 0.0942 0.1257 0.1571
14 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
Exercises 5. 5.1). Create a script to plot the shape given in equation (4) of the
mode m = 3.
5.2). The mode shapes for velocity standing waves in a cylinder may be approx-
imated by the equation:
(5) y = cos(mx)
Create a script to plots this shape of the mode m = 5.
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 15
5.3). Create a script to plots these shapes for the modes m = 1, m = 2 and
m = 3 all on the same graph.
5.4). Create a script to plots the mode shape for m = 1 with different spacings
for the x range (for instance by defining xlow = 0:0.1:1; and xhigh = 0:0.01:1;).
4 5 6
It is conventional to use capitals for matrices. Note that typing a is will not get
you the contents of A (i.e. MATLAB is case-sensitive). You can also make a
matrix using multiple vectors within square brackets, as long as the vectors are
the same length. For instance we can make a matrix, Y, consisting of two row
vectors (y 1 and y 2) using:
>> x = 0:0.01:1;
>> m = 1;
>> y_1 = sin(m*pi*x);
>> m = 2;
>> y_2 = sin(m*pi*x);
>> Y = [transpose(y_1), transpose(y_2)];
>> plot(x,Y)
>> shg
Here we have transposed the row vectors to make column vectors and put them
alongside one another using the comma. Note that the plot command in MATLAB
plots each column in a vector with a different colour, so the plot should look the
same as the one produced in section 6.
Ranges can be selected in a similar way to vectors. To show the first 6 rows of
the two columns in Y we can type:
>> Y(1:6,1:2)
ans =
0 0
0.0314 0.0628
0.0628 0.1253
0.0941 0.1874
0.1253 0.2487
0.1564 0.3090
We can check the size or dimension of a matrix, vector or variable using the size
command as follows:
>> size(m)
ans =
1 1
>> size(y_1)
ans =
1 101
>> size(y_2)
ans =
1 101
>> size(transpose(y_1))
ans =
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 17
101 1
>> size(Y)
ans =
101 2
The size command thus returns a vector whose first entry is the vertical height of
the matrix (or number of rows) and whose second entry is the horizontal width
of the matrix (or number of columns) so that Y has dimensionality 101 2 in
this case. Note that vectors can be though of as matrices with a size of one along
one dimension and variables (like m = 2) can be thought of as matrices with
dimensionality 1 1.
Exercises 7. 7.1). Create a script to plot a matrix containing the shapes for the
guitar string modes m = 1, 2, 3, 4 and 5 on the same graph.
8. Frequency
You will notice that the different standing waves mode shapes on a guitar string
have different wavelengths. Next we will discuss the concept of frequency in order
to work towards constructing a wave which follows a sine wave profile over time
which we can the listen to. The frequency of a wave is defined as the number
of cycles per second for a wave, and we will set this equal to a variable called f .
Initially we will try 440 samples per second, and this is expressed in scientific units
as 440 Hz.
If we have a frequency (or number of cycles per second) then we can work out
the time taken for a single cycle, known as the period time using the equation:
1
(6) T =
f
In the case of a 440 Hz vibration the period time will be:
>> f = 440;
>> T = 1/f
T = 0.0023
so one cycle of a sine wave at 440 Hz will take 0.0023 seconds, or 2.3 milliseconds.
8.1. Sampling frequency. In order to create a sound on a computer we need to
first set a number of samples per second for approximating the wave shape and
put this into a variable called f s. Initially we will use 44100 samples per second
which can also be expressed as 44100 Hz or 44.1 kHz. This is the standard sample
rate for CD quality audio.
We can then compute the time between samples using equation (6) which will
be ts = 1/f s. Try checking this value in the command line as follows:
>> fs = 44100;
>> ts = 1/fs
ts = 2.2676e-05
18 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
8.2. Making a sine wave plot. The total time duration of our sine wave can be
defined as one second and stored in a variable called t dur. We will initially set
this equal to the period time of the wave, so that one cycle will fit into our time
duration. Calculating the total number of samples in the sound is then a matter
of dividing the total time duration by the number of seconds between each sample.
As an example, in 1/440 of a second the number of samples, N , will be calculated
as follows:
>> fs = 44100;
>> t_dur = 1/440
t_dur = 0.0023
>> N = t_dur/ts
N = 100.2273
The should be just over 100 samples in one cycle of a sine wave of frequency 440
Hz at a sample rate of 44100 Hz. It doesnt make any sense to have a fraction of
a sample on the end so we have to round the answer to the nearest integer using
the round function which is built in to MALTAB:
>> N = round(t_dur/ts)
N = 100
Following this we create a vector of N time points. The vector of time points
should have a first value of zero, a second value of ts, a third sample of 2ts and
so on, so the N th sample will have a value of (N 1)ts. This can be achieved by
first making a vector of N integers, then multiplying by the sampling period.
>> fs = 44100;
>> ts = 1/fs;
>> n = [0:N-1];
>> t = ts*n;
Checking the first 6 values in the time vector should now give:
>> t(1:6)
ans =
1.0e-03 *
0 0.0227 0.0454 0.0680 0.0907 0.1134
Now we can make a vector containing the sine wave of frequency f and plot the
results against time as follows:
>> p = sin(2*pi*f*t);
>> plot(t,p)
>> shg
8.3. Making a sine wave sound. Making a sound file of the sine wave vector,
p, can be done using the built in wavwrite function. This function interprets
columns of numbers as audio signals. In order to make our row vector sine wave
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 19
into a column we must use the transpose command, replacing p with the column
vector version as follows:
>> p = transpose(p);
Next we write the column vector using the wavwrite function:
>> wavwrite(p, fs, mysinewave.wav)
Make sure you do include the single quotation marks this time when you type
in this command. Now type ls (without quotes) into the command line to list
the contents of the directory you are in and you should see mysinewave.wav is
one of the files present. This is a wav file; an uncompressed sound file that can
be played back in any audio software. Note that we are making files which have
the potential to sound piercing. Turn down the volume on your audio equipment
or remove your headphones before playing sounds for the first time to prevent
unpleasant experiences involving loud, piercing sounds causing ringing in the ears
(tinnitus) or hearing damage.
Try opening the file (using the Finder if you are on Mac or using Start >
Documents on Windows, then double clicking on the file). You should hear a very
short sound. While we set a frequency of 440 Hz, the duration was so short that
the pitch will not be clear. If we want to hear a clear pitch we must do this process
with longer duration (say t dur = 1 for one second duration).
Exercises 8. 8.1). Make a script to create a two second sine wave of frequency
110 Hz and store it in a wav file.
8.2). Make a script to create a one second sine wave of frequency 220 Hz and
store it in a wav file (with a different name).
8.3). Make a script to create sine wave of frequency 330 Hz that lasts for half a
second and store it in a wav file (with a different name again).
8.4). Have a listen to the three files you have created above. The 220 Hz sine
wave should sound higher in pitch than the 110 Hz sine wave. This frequency
ratio of 2:1 corresponds to a difference in perceived pitch which is known as an
octave. The 330 Hz sound will sound higher again. This time the ratio of 3:2
with the 220 Hz will produce a pitch difference known as a perfect fifth.
8.4. Making a function. We have created several very similar scripts now to do
very similar jobs but with slightly different input definitions (for frequency and
duration in this case). It is often useful to create a single function which works for
different input values. For instance we can create a MATLAB function to create
a sine wave of a particular sample rate, duration and frequency by creating a file
with the name mysine.m in a text editor and typing the following code inside it:
function [p, t] = mysine(fs, f, t_dur)
%fs is the sample rate (Hz)
%f is the frequency of the sine wave (Hz)
%t_dur is the duration of the sound (seconds)
20 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
8.5. Clipping. You may have seen a warning about the file being clipped in
completing section 8.4 above. Sine waves have a minimum and maximum of pre-
cisely -1 and 1 but the wav file format can only store values between roughly -1 and
1 with a finite precision (or bit resolution) and the slight discrepancy produces
the warning. Assuming the file mysine.m has been created successfully using the
code above then we can check the minimum and maximum of the vector, p, as
follows:
>> fs = 44100;
>> f = 880;
>> t_dur = 2;
>> [p,t] = mysine(fs, f, t_dur);
>> min(p)
ans = -1.0000
>> max(p)
ans = 1.0000
As the maximum amplitude is indeed 1 there wont be audible effects due to the
clipping.
If on the other hand we create a waveform and multiply by a factor of, say,
4 before writing the wav file, then we should hear audible differences. Try the
following:
>> fs = 44100;
>> f = 220;
>> t_dur = 1;
>> [p, t] = mysine(fs, f, t_dur);
>> wavwrite(p, fs, mysine220.wav)
>> wavwrite(4*p, fs, myclipped220.wav)
This time the wave 4*p is producing an input with a range of -4 and 4 meaning that
the wav file format (which can only store numbers in the range between -1 and 1)
will clip the top and bottom of the waveforms, causing a sort of distortion called
clipping. This is similar to the concept of saturation in amplifiers where the
output clips or saturates when the desired output exceeds the operating range
of the amplifier (which in turn depends on the amplifier power supply). Have a
listen to the two files you have produced. You will notice that, as well as sounding
louder, the file myclipped220.wav has a brighter tone quality while retaining the
same pitch.
We can read the contents of the wav file back into MATLAB as a variable called
p4 using the wavread function, and this can then be compared to 4*p using a
plot command:
>> [p4, fs] = wavread(myclipped220.wav);
>> plot(t, 4*p, t, p4)
>> shg
22 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
The plot shows how the wav file has been clipped outside the range -1 and +1 and
this is especially clear if we limit the x axis range to just show one period using
the xlim command:
>> xlim([0, 1/f]);
>> shg
8.6. Using the fft command for Fourier transforms. We can analyse the
frequency spectrum of sounds in MATLAB using Fourier transforms with the fft
command. Assuming that the wav files have been created correctly from section
8.5 then a plot of the frequency spectrum should be produced using the following
code:
>> [p, fs] = wavread(mysine220.wav);
>> N = length(p);
>> n = [0:N-1];
>> fvec = n*fs/N;
>> pfft = fft(p);
>> plot(fvec,abs(pfft))
Here we have used three new functions: the fft command which computes a vec-
tor containing the frequency spectrum of the input vector, the length command
which returns the number of entries in the input vector, and the abs command
which returns the magnitude (or absolute value) of a complex number and this
is necessary because the fft command returns complex numbers. Note that the
left-hand side of the resulting plot shows one peak and this corresponds to a fre-
quency of 220 Hz. This indicates that the sound stored in the wav file was indeed
a sine wave at 220 Hz. The right-hand side of the plot shows a mirror image of the
left-hand side because frequencies greater than half of the sample rate cannot be
measured uniquely. We can label the axes using the xlabel and ylabel com-
mands and limit the range of the plot to show the frequency peak in more detail
as follows:
>> xlabel(Frequency (Hz))
>> ylabel(Amplitude)
>> xlim([200, 240])
Next we can try plotting the frequency spectrum of the clipped file as follows:
>> [p4, fs] = wavread(myclipped220.wav);
>> p4fft = fft(p4);
>> plot(fvec,abs(p4fft))
>> xlim([0, 2000])
This time we can see multiple peaks and these are at 220 Hz, 3 220 Hz = 660
Hz, 5 220 Hz = 1100 Hz, 7 220 = 1540 Hz and 9 220 Hz = 1980 Hz. These
peaks are called odd harmonics in that they are odd integers multiplied by the
fundamental frequency of 220 Hz. The clipping generated by the wavwrite process
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 23
9. Wavelength
If a sine wave is produced in air, say by loudspeaker then the sound travels
away from the source as a travelling wave. There will be one period time T = 1/f
between one peak of the wave being produce and the next peak of the wave being
produced for a frequency of f . The first peak will have travelled a distance of
c
(7) = cT =
f
24 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
where c is the speed of wave propagation (and c 340 m/s is the speed of sound
in air). The value is called the wavelength of the wave. If, on the other hand,
we somehow know the wavelength of a sound we can work out the frequency using
a rearrangement of equation (7):
c
(8) f=
9.1. Travelling waves, standing waves and reflection. So far we have en-
countered standing waves, such as those on a guitar string, and travelling waves,
such as the waves which travel from a source to a listener. The relationship be-
tween these two forms of sound are useful to study. When a sound wave collides
with wall it is reflected in a similar way to light being reflected from a mirror. The
wall doesnt act as a perfect acoustic mirror in that sound with low frequency
bends around objects due to a process called diffraction and different surfaces
absorb different frequencies to different extents.
Once a wave is reflected, we get two travelling waves on top of each other: one
going towards the wall and one going away from the wall. If the two waves have the
same amplitude then the result is alternating areas of constructive and destructive
interference. The wave vibrates in the areas of constructive interference while
appearing to not vibrate in the areas of destructive interference. This is a what
we mean by a standing wave. For the moment the main thing to note is that
the wavelength and frequency of both standing waves and travelling waves obey
equation (8) as standing waves are simply two travelling waves superimposed.
When a positive acoustic pressure bounces off a wall in a room then the reflection
will also have a positive pressure. We say that the wave is reflected in phase.
Consider waves on a string fixed at both ends. A travelling wave featuring an
upwards motion of the string hitting a fixed end will supply an upwards force
to the support which are fixing the end of the string. The string will receive an
equal and opposite force from the support (and this is an example of Newtons
third law). The motion on the string will then show a downwards motion for the
reflected travelling wave. We say that the wave is reflected out of phase in this
case.
9.2. The frequencies of the modes of a string with fixed ends. As waves
are reflected out of phase from the ends, the standing wave shapes must be zero
at the ends. This is exactly what we saw in section 6. We will now consider the
wavelength of these modes, define the speed of wave propagation on a string and
calculate the frequency of vibration of the modes. If we define the string length as
L then the fundamental mode will feature half a wavelength so
1
(9) L= , 1 = 2L
2
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 25
9.3. Waves in pipes. When a positive acoustic pressure bounces of the closed end
of a cylinder the wave is reflected in phase (i.e. with a positive acoustic pressure)
so that the closed end behaves in the same way as a wall in a room. If a travelling
waves arrives at the open end of the tube the opposite happens in that the wave
is, to a first approximation, reflected out of phase back down the cylinder. This
is, initially, rather a surprising statement. If we walk down a corridor and out of
an open door at the end then we do not experiencing a force sending us back in
the other direction upside-down!
Wave motion is strange and sometimes unintuitive. The fact that a positive
acoustic pressure is reflected from an open end as a negative acoustics pressure is
due to changes in the area that the pressure wave may occupy. Waves in a pipe
will reflect whenever the cross-section area changes, for instance. The reflection is
in phase if the cross-section decreases and the reflection is out of phase if the cross-
section increases. While this is very hard to understand, study of this phenomenon
in acoustics in strongly related to the subject of quantum mechanics where the
26 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012
Schrodinger equation shows how very small particles behave in very strange, wave-
like manner. Electrons inside atoms behave in this way, occupying standing wave
states. The reason we find wave-like behaviour strange is because we are not small
enough! Acoustics is just one of the subjects that can help educate us.
9.4. Using a for loop to show travelling waves. We will now create a series
of plots so that travelling waves are displayed on the screen. Make a script file and
put the following code into it:
%Clear any old variables (in case we use them by accident):
clear
%Plotting updates per second (Hz):
fs = 25;
%Number of points in the plot along x axis:
Lx = 100;
%Frequency (Hz):
f = 0.5;
%Duration of movie (seconds):
t_dur = 5;
%Wavelength:
lambda = 2*Lx/5;
%for loop:
for ind = 0:Nt-1
%Time now:
t = ind/fs;
%Travelling wave in forward direction:
pfor = sin(w*t - k*x);
%Do plot:
plot(x, pfor)
%Bring graph to top of the screen if necessary:
shg
%Delay for ts seconds so plot moves at (roughly) the correct speed:
pause(1/fs)
INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012 27
end
This script plots a travelling wave that travels to the right.
ans = 250
This may not look like it has achieved much at first inspection, but we can check
what class has been created using the command whos (which is different from the
command who in that it shows you information on the variables in long rather
than short form):
>> who
Your variables are:
ans f
>> whos
Name Size Bytes Class Attributes
ans 1x3 6 char
f 1x1 8 double
So we can see that the answer is a member of the class char and this means that it
can be used as part of a file name. We can use square brackets to contain a vector
with a combination of quotes and num2str commands separated by commas as
follows:
>> [sine,num2str(f),.wav]
ans = sine250.wav
Using this technique we write a wav file using the wavwrite command incorporating
the variables f and f s in the file name by editing the function we created in section
8.4 with the new bottom line in the following code:
function [p, t] = mysine(fs, f, t_dur)
%fs is the sample rate (Hz)
%f is the frequency of the sine wave (Hz)
%t_dur is the duration of the sound (seconds)
%p is the vector of the sine wave
%t is the vector of times
11. Answers
Answers to Selected Exercises. 1.1). We need to work out the distance to the
castle and back:
>> 34+34
ans = 68
so d = 68 m and then work out the time using t = d/c which is:
>> 68/340
ans = 0.2000
so the time before we hear the echo is 0.2 s.
1.2). Rearranging equation (1) we get d = ct so:
>> 340*0.3
ans = 102
gives the answer as 102 m.
1.3). The time between echoes is:
>> 1/180
ans = 0.0056
so 0.0056 seconds or 5.6 milliseconds. The distance travelled by sound in between
each echo must be d = ct:
>> 340*0.0056
ans = 1.9040
so the distance between the walls must be half this (as the sound must travel to
the other wall and back to make each echo:
>> 1.9040/2
ans = 0.9520
so the distance between the walls is 0.9520 m or 95.2 cm.
1.4). Here the tape speed is c = 2.5 cm/s and the taken for echoes to appear is
t = d/c so using d = 5 cm we have:
>> 5/2.5
ans = 2
30 INTRODUCTION TO MATLAB
c JONATHAN A. KEMP 2012