September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
Pre

Lab and Warm

Up:
Read
the Pre

Lab and Warm

up sections of this lab assignment and go
over all exercises in the Pre

Lab section before going to your
actual
assigned lab session.
Verification:
The Warm

up section of each lab must be completed during
your assigned Lab time.
When you have completed a step
and want verification
, sim
ply demonstrate the step to the
instructor.
Lab Report:
It is only necessary to turn in a repo
rt on
Section
s
with
graphs and short
explanations. You are asked to label the
axes of your plots and
include a title for every plot.
If you
are unsure
about what is expected, ask the
instructor
.
1 Pre

Lab
In this first week, the Pre

Lab will be
easy
. Make sure that you read through the information below
prior to coming to lab.
1.1
Overview
MATLAB will be used extensively in all the labs. The primary goal of this lab is to
get
familiarize
d
with
MATLAB.
Use
the
r
eference
and
i
ntroduction
manuals
as made available on black board
(see course documents:
Matlab stuff
) or
http://www.mbfys.ru.nl/~robvdw/CNP04/MATLAB_STUFF/
.
Here are three specific goals for this lab:
1. Learn basic MATLAB commands and syntax, including the help
system.
2. Learn to write and ed
it your own script files in MATLAB, and run them as commands.
3. Learn a little about advanced programming techniques for MATLAB, i.e., vectorization.
1.2
Getting Started
After logging in,
as '
gas
t
' (password: '
noprint
', go to d:
\
prac
\
matlabR13. Y
ou c
an start
MATLAB by double

clicking on a
MATL
AB icon.
When MATLAB has started you'll find yourself in the directory
d:
\
prac
\
matlabR2007a
\
work
Now first make a new directory:
‘
mymatlab
’
by typing in the
<
Command Window
>
mkdir mymatlab
, fo
llowed by
cd mymatlab
.
You are now in
:
’
d:
\
prac
\
matlabR13
R2007a
\
work
\
mymatlab
’
.
This will be the directory in which you will create your own files and figures
.
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
Now it's time to exte
nd the path of M
atlab. You will have to include in the current path you
r new
directory, as well as the custom routines that have been prepared f
or this course. These routines,
with which you can create elementary auditory stimuli are found
on the network harddisk
D
.
They will be found in the directory:
d:
\
prac
\
matlabR2007
a
\
CNP04.
A
dd this directory to your
<Matlab
path
>
. You can add directories to your
<Matlab
path
>
with the file menu in the window in
the top

left corner of your screen.
Store all files that you have made on your own USB stick
or other medium of your own.
NOTE:
When you shut off the computer all these settings are lost,
and the disk is entirely erased. NOTHING will be stored!!!
1.3
Introduction to Matlab
The following steps will introduce you to MATLAB.
(a)
View the MATLAB introduction by typing intro at t
he MATLAB prompt. This short
introduction will demonstrate some of the basics of using MATLAB.
(b)
Run the MATLAB help desk by typing helpdesk. The help desk provides a hypertext
interface to the MATLAB documentation. The MATLAB preferences can be set to use
Internet Explorer as the browser for help. Two links of interest are Getting Help (at the
bottom of the right

hand frame), and Getting Started which is under MATLAB in the left

hand frame.
(c)
Explore the MATLAB help capability available at the command lin
e. Try the following:
help
help plot
help colon %<

a VERY IMPORTANT notation
help ops
help zeros
help ones
lookfor filter %<

keyword search
help matlab/general

General purpose commands.
help matlab/ops

Operators and special characters.
h
elp matlab/lang

Programming language constructs.
help matlab/elmat

Elementary matrices and matrix manipulation.
NOTE: it is possible to force MATLAB to display only one screen

full of information at once
by issuing the command
more
on
).
(d)
Run the MAT
LAB demos:
type
demo
and explore a variety of basic MATLAB
commands and plots.
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
(e)
Use MATLAB as a calculator. Try the following:
pi*pi

10
sin(pi/4)
ans ˆ 2 %<

"ans" holds the last result
(f)
Do variable name assignment in MATLAB. Try the following:
x
= sin( pi/5 );
cos( pi/5 ) %<

assigned to what?
y=sqrt(1

x*x )
ans
2
Warm_up
2.1
MATLAB Array Indexing
(a)
Make sure that you understand the colon notation.
Jkl = 0 : 6
Jkl = 2 : 4 : 17
Jkl = 99 :

1 : 88
Ttt = 2 : (1/9) : 4
Ttt = Ttt’
tpi = pi * [
0:0.1:2 ];
(b)
Extracting and/or inserting numbers into a vector is very easy to do. Consider the following
definition of xx:
xx = [ zeros(1,3), linspace(0,1,5), ones(1,4) ]
xx(4:6)
size(xx)
length(xx)
xx(2:2:length(xx))
Explain the results echoed
from the last four lines of the above code.
(c)
Observe the result of the following assignments:
yy = xx; yy(4:6) = pi*(1:3)
Now write a statement that will take the vector xx defined in part (b) and replace the even
indexed elements (i.e., xx(2), xx(4)
, etc) with
0.
Use a vector replacement, not a loop.
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
2.2
MATLAB Script Files
(a)
Experiment with vectors in MATLAB. Think of the vector as a set of numbers. Try the
following:
xk = cos( pi*(0:11)/4 ) %<

comment: compute cosines
Explain how the differ
ent values of cosine are stored in the vector xk. What is xk(1)? Is
xk(0)
defined?
NOTE
: the semicolon at the end of a statement will suppress the echo to the screen. The
text following the %is a comment; it may be omitted.
(b)
(A taste of vectorization)
Loops can be written in MATLAB, but they are NOT the most
efficient way to get things done. It’s better to always avoid loops and use the colon
notation instead. The following code has a loop that computes values of the cosine
function. (The index of yy()
must start at 1.) Rewrite this computation without using the
loop (follow the style in the previous part).
yy = [ ]; %<

initialize the yy vector to be empty
for k=

5:5
yy(k+6) = cos( k*pi/3 )
end
yy
Explain why it is necessary to write
yy(k+6
)
. What happens if you use yy(k)instead?
(c)
Plotting is easy in MATLAB. The basic plot command will plot a vector y
versus a vector
connecting successive points by straight lines. Try the following:
x=[

3

1 013];
y = x.*x

3*x;
plot(x, y );
Use
help ar
ith
to learn how the operation xx.*xx works when xx is a vector;
compare to matrix multiply.
(d)
Use the built

in MATLA
B editor (on Windows

95/98/NT)
to create a script file called
mylab1.mcontaining the following lines:
tt=

1: 0.01: 1;
xx =
sin
( 5*pi*tt
);
zz =
cos
( 5*pi*tt );
plot( tt, xx, ’b

’, tt, zz
, ’r

’ ), grid on
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
%<

plot a sinusoid
title(’TEST PLOT of a SINUSOID’)
xlabel(’TIME (sec)’)
What is the
phase and amplitude
and frequency of xx
? Make a
calculation of the phase
from a time

sh
ift measured on the plot.
Also the command
’hold on’
is useful when
plotting several functions within the same plot.
(e)
Run your script from MATLAB. To run the file mylab1that you created previously, try
mylab1
%<

will run the commands in the file
typ
e mylab1
%<

will type out the contents of
%
<

mylab1.m to the screen
3
Manipulating Sinusoids with MATLAB
3.1
Create a pure tone.
The exercises in this section involve sound signals, so you should bring headphones to the lab for
listening.
(a)
Run the
MATLAB sound demo by typing
’
xpsound
’
at the
MATLAB prompt. If you
are unable to hear
the sounds in the MATLAB demo then ask an instructor for help.
When unsure about a command, use help.
(b)
Now generate a tone (i.e., a sinusoid) in MATLAB and listen to it
with the
soundsc()
command.
The first two lines of code in part 2.2(d) create a vector xx
of values of a 2.5 Hz
sinusoid.
The frequency of your sinusoidal tone should be 2000 Hz and its duration should be 0.9
sec. Use a sampling rate (
F
s
)
equal to 11025
[
samples
/
sec
]
.
The sampling rate dictates the time interval between time points, so the time

vector
should be defined as follows:
t = 0:(1/F
s):dur;
where
fs
is the desired sampling rate a
nd
D
ur
is the desired duration [in seconds]
.
Read the online
help
for both
sound
()
and
soundsc()
to get more information on
using this command. What is the length (number of samples) of your
tt
vector?
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
3.2
Display Sinusoids
.
Include a short summary of this Section
with plots in your Lab report.
Write a MATLAB scrip
t
file to
do steps (a) through (
i
) below. Include a listing of the script file with your report.
(a)
Graphically display a sinusoid (i.e., “pure tone”) from
T
1,

10 [msec]
,
up to
T
2,
90
[msec]
.
Use a sampling frequency,
Fs
,
of 4000 Hz. Give the
formulas that c
ompute
(1)
the sample time
T
, (2) the duration,
Dur
, and (3) the length of the single,
L
(i.e.,
number of samples).
Notice that
T1
and
T2
are given in [msec].
Now it should be
possible to generate a time vector,
tt
,
to cover the range

10 to 90 msec with a
interval
T
.
(b)
Make a plot of a sinus function as a fat
(‘linewidth’, 2)
red line
(‘r

‘)
, with
a frequency of 150 Hz, a phase of
pi/6
and an amplitude of 1.5, running from

10 to
+90 ms.
How many cycles do you expect to see.
(c)
Provide the correct x

label and
y

label and title texts to the
figure.
(d)
Keep the figure
(type 'hold on')
, and now plot another sinus function as a fat
green line, with a frequency of 80 Hz, a phase of
pi/3
and amplitude 0.6
(e)
Make a plot, in the same figure, of the sum of the two previou
s sinusoids in black.
(f)
Create a
program (name this program:
twosines_2a.m
) that implements the plots of
the previous exercise, but now for an arbitrary time axis (from 'start' to 'end', in ms, but
your time array will be sampled at 50 kHz, i.e. at 20 micro
second intervals), for arbitrary
frequencies ('f1' and 'f2'), amplitudes ('A1' and 'A2'), and phases (‘p1’, and ‘p2’). These
values are given as inputs to the function. Make some obvious input error checks like:
end should be greater than start, and f1 and
f2 should be greater than zero).
(g)
Same program as in [a] (
twosines_2b.m
), but now the three plots are displayed as
different sub

plots within the same figure.
(h)
S
ame as in [g
], but you store the three sine waves as 'wav files', and at the end of the
progr
am they are played over the headphones.
For this, you can use the M
atlab routine
playsound.m
(i)
S
ame as in [h
],
(
twosines_2c
.m
),
but you create a simple loop in which the user is
asked to type in the necessary parameter values one by one:
start, end, f1, pha
se1, f2,
phase2, A1 and A2
hint: you want to use the
INPUT
comman
d
(
use
help
to learn
on
how to use it)
.
Also the
eval
command may be helpful.
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
%%First enter the parameters of the problem: we're sampling 4000 times per time
unit (probably a second) = Fs
(sampling frequency)
%%so each time sample covers 1/4000 of a second = T
%%the length of the entire signal that we have to look at is 1000 samples
%%we make a time vector that has an entry for each time sample in the whole
signal time

so goes from 0 to t
he (signal length

1)
%%(because we're starting to count from zero instead of 1) and has total time
samples number of entries (which should equal the length
%%which are listed in time units (so here, fraction of a second)
%%%%%% THE CODE
Fs = 4000;
% Sampling frequency
T = 1/Fs; % Sample time
Dur = 0.100; % Sample duration
L = Dur/T; % Length of signal
t = (0:L

1)*T; % Time vector
t_msec=(t*1000)

10;
%convert time vector in msec starting at

10 msec
% Now we're going to create an idealized signal, which is composed of two parts
% 150 Hz sinusoid at 1.5 amplitude and phase pi/6
% and
% 80 Hz sinusoid at 0.6 amplitude and phase pi/3
% as a f
unction of time.
%Create the signal and take a look at its components (in the firstwindows) and the summed whole
signal.
x1 = 0.6 * sin( 2 * pi * 150 * t + pi/6 );
x2 = 0.6 * sin( 2 * pi * 80 * t + pi/3 );
x1x2=x1+x2;
figure('NumberTitle','off');
plot(t_msec,x1,'r

','LineWidth',2);
hold on;
plot(t_msec,x2,'b

','LineWidth',2);
plot(t_msec,x1x2,'k

','LineWidth',2);
axis([

10 90

2 2]);
xlabel('Time [msec]','Fontsize',13);
set(gca,'YT
ick',[

2:.5:2],'YTickLabel',…
{'

2.0','1.5','1.0','0.5','0.0','+0.5','+1.0','+1.5','+2.0'})
ylabel('Amplitude [a.u.]','Fontsize',13);
set(gca,'FontName','Arial','FontSize',13,'LineWidth',2);
grid
%%
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
%%
close all
clear all
clf
A1=1.5;
A2=0.6;
F1=500;
% Frequency in Hz
F2=600; % Frequency in Hz
P1=pi/6;
P2=pi/3;
T1=10; % start time in msec
T2=50; % end time in msec
%%First enter the parameters of the problem: we're sampling 4000 times per time unit (probably a
second) = Fs (sampli
ng frequency)
%%so each time sample covers 1/4000 of a second = T
%%the length of the entire signal that we have to look at is 1000 samples
%%we make a time vector that has an entry for each time sample in the whole signal time

so goes
from 0 to the (sig
nal length

1)
%%(because we're starting to count from zero instead of 1) and has total time samples number of
entries (which should equal the length
%%which are listed in time units (so here, fraction of a second)
Fs = 8000; %
Sampling frequency in Hz
T = 1 / Fs; % Sample time
Dur = abs(T1

T2) / 1000; % Signal duration
L = Dur / T; % Length of signal
t = (0:L

1) * T; % Time vector
t_msec=(t*1000)+T1;
%convert time vector in msec starting at

10 msec
% Now we're going to create an idealized signal, which is composed of two parts
% F1 freq sinusoid at A1 amplitude and phase P1
% and
% F1 freq sinusoid at A2 amplitude and phase P2
% as a func
tion of time in msec.
% Now create the summed whole (black) and display its components (red & blue).
x1 = A1 * sin( 2 * pi * F1 * t + P1 );
x2 = A2 * sin( 2 * pi * F2 * t + P2 );
x1x2 = x1 + x2;
x=[x1' x2' x1x2'];
fig_title=[ 'pure ton
e at ' num2str(F1)
'pure tone at ' num2str(F2)
'Sum of two tones'];
figure('NumberTitle','off');
for i=1:1:3
subplot(3,1,i)
hold off;
h=plot(t_msec,x(:,i)','

','LineWidt
h',2);
if(i==1)
set(h,'Color',[1,0,0])
elseif(i==2)
set(h,'Color',[0,0,1])
elseif(i==3)
set(h,'Color',[0,0,0])
end
title(fig_tit
le(i,:),'FontName','Arial','FontSize',13);
Amp_range=abs(max(x1x2)

min(x1x2))*0.1; % calulates 10% of the summed amplitude range
axis([T1 T2 min(x1x2)

Amp_range max(x1x2)+Amp_range]);
xlabel('Time [msec]','Fontsize',13);
ylabel('Amplitude [a.u.]','Fontsize',13);
set(gca,'FontName','Arial','FontSize',13,'LineWidth',2);
grid
end
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
%%
close all
clear all
clf
cd 'E:
\
PROJECTS2007
\
COLLEGE_2007
\
PRACTICA_AUDITORY_PERCEPTION
\
CNPA04
\
'
% F1 = input('enter F
1 ');
% P1 = input('enter P1 ');
% P1 = pi/P1;
%
% F2 = input('enter F2 ');
% P2 = input('enter P2 ');
% P1 = pi/P2;
%
% A1 = input('enter A1 ');
% A2 = input('enter A2 ');
%
% T1 = input('enter T1 ');
% T2 = input('enter T2 ');
for i=1:1:2
e
val(['F' num2str(i) '= input(''enter F' num2str(i) ' '')']);
eval(['P' num2str(i) '= input(''enter P' num2str(i) ' '')']);
eval(['A' num2str(i) '= input(''enter A' num2str(i) ' '')']);
eval(['T' num2str(i) '= input(''enter T' num2str(i) ' '
')']);
end
% A1=0.4;
% A2=0.6;
% F1=500; % Frequency in Hz
% F2=600; % Frequency in Hz
% P1=pi/6;
% P2=pi/3;
% T1=0; % start time in msec
% T2=2000; % end time in msec
%%First enter the parameters of the problem: we're sampli
ng 4000 times per time unit (probably a
second) = Fs (sampling frequency)
%%so each time sample covers 1/4000 of a second = T
%%the length of the entire signal that we have to look at is 1000 samples
%%we make a time vector that has an entry for each time
sample in the whole signal time

so goes
from 0 to the (signal length

1)
%%(because we're starting to count from zero instead of 1) and has total time samples number of
entries (which should equal the length
%%which are listed in time units (so here, f
raction of a second)
Fs = 8000; % Sampling frequency in Hz
T = 1 / Fs; % Sample time
Dur = abs(T1

T2) / 1000; % Signal duration
L = Dur / T; % Length of signal
t = (0:L

1
) * T; % Time vector in sec
t_msec=(t*1000)+T1; %convert time vector in msec starting at

10 msec
% Now we're going to create an idealized signal, which is composed of two parts
% F1 freq sinusoid at A1 amplitude and phase P1
% and
% F1 freq sinusoid at A2 amplitude and phase P2
% as a function of time in msec.
% Now create the summed whole (black) and display its components (red & blue).
x1 = A1 * sin( 2 * pi * F1 * t + P1 );
x2 = A2 * sin( 2 * pi * F2 * t +
P2 );
September 11, 2007
Lab 01: Introduction to MATLAB / SOUND
x1x2 = x1 + x2;
x=[x1' x2' x1x2'];
figure('NumberTitle','off');
for i=1:1:3
subplot(3,1,i)
hold off;
h=plot(t_msec,x(:,i)','

','LineWidth',2);
if(i==1)
set(h,
'Color',[1,0,0])
elseif(i==2)
set(h,'Color',[0,0,1])
elseif(i==3)
set(h,'Color',[0,0,0])
end
Amp_range=abs(max(x1x2)

min(x1x2))*0.1; % calulates 10% o
f the summed amplitude range
axis([T1 T2 min(x1x2)

Amp_range max(x1x2)+Amp_range]);
xlabel('Time [msec]','Fontsize',13);
ylabel('Amplitude [a.u.]','Fontsize',13);
set(gca,'FontName','Arial','FontSize',13,'LineWidth',2);
grid
end
%% PLAY SOUND
clc
sound(x1,Fs,16);
sound(x2,Fs,16);
sound(x1x2,Fs,16);
%% CREATE 32 BIT WAV FILE with Normalized Amplitude
clc
wavwrite(x1,Fs,32,[ num2str(F1) 'Hz' ]);
wavwrite(x2,Fs,32,[ num2str(F2) 'Hz' ]);
wavwrite(x1x2,
Fs,32,[ num2str(F1) '

' num2str(F2) 'Hz' ]);
Comments 0
Log in to post a comment