Coding the Star Spangled Banner in MATLAB


Using the sound function in Matlab, we are able to create a song using sine waves with specific frequencies. Each note has certain frequency that corresponds to it and through sine waves and putting it into the sound function we are able to create a song. Below is an example of MATLAB code that can be used to play the star spangled banner.

This section of the code sets the timing for the notes, each time represents what the length of a beat will be.

delta = 1/8192;
t1 = 0:delta:1/2;
t2 = 0:delta:1;
t3 = 0:delta:1/3;
t4 = 0:delta:1/4;
t5 = 0:delta:3/4;
tf = 0:delta:2;

Below is the declarations for all of the notes I use in this song. Notice that t is multiplied by different numbers representing the different frequencies of all the notes.

A5 = sin(2*pi*440*t1);
C5 = sin(2*pi*523*t1);
D5 = sin(2*pi*587*t1);
E5 = sin(2*pi*659*t1);
G5 = sin(2*pi*784*t1);

Notice that some notes are declared twice using different "t"s. This is because during certain instances in the song, the same note needs to be held for different lengths of time.

B52 = sin(2*pi*494*t2);
C52 = sin(2*pi*523*t2);
E52 = sin(2*pi*659*t2);
G52 = sin(2*pi*784*t2);
B62 = sin(2*pi*988*t2);
C62 = sin(2*pi*1047*t2);
D62 = sin(2*pi*1175*t2);
E62 = sin(2*pi*1319*t2);
F62 = sin(2*pi*1397*t2);
G62 = sin(2*pi*1568*t2);

FS = sin(2*pi*739.989*t1);
FS6 = sin(2*pi*1479.978*t1);

B53 = sin(2*pi*494*t3);
C53 = sin(2*pi*523*t3);
E53 = sin(2*pi*659*t3);
G53 = sin(2*pi*784*t3);
A63 = sin(2*pi*880*t3);
B63 = sin(2*pi*988*t3);
C63 = sin(2*pi*1047*t3);
D63 = sin(2*pi*1175*t3);
E63 = sin(2*pi*1319*t3);
F63 = sin(2*pi*1397*t3);
G63 = sin(2*pi*1568*t3);

A54 = sin(2*pi*440*t4);
B54 = sin(2*pi*494*t4);
G54 = sin(2*pi*784*t4);
E54 = sin(2*pi*659*t4);
A64 = sin(2*pi*880*t4);
B64 = sin(2*pi*988*t4);
C64 = sin(2*pi*1047*t4);
D64 = sin(2*pi*1175*t4);
E64 = sin(2*pi*1319*t4);
F64 = sin(2*pi*1397*t4);
G64 = sin(2*pi*1568*t4);

C55 = sin(2*pi*523*t5);
E55 = sin(2*pi*659*t5);
C65 = sin(2*pi*1047*t5);
C6f = sin(2*pi*1047*tf);

A6 = sin(2*pi*880*t1);
B6 = sin(2*pi*988*t1);
C6 = sin(2*pi*1047*t1);
D6 = sin(2*pi*1175*t1);
E6 = sin(2*pi*1319*t1);
F6 = sin(2*pi*1397*t1);
G6 = sin(2*pi*1568*t1);

p = sin(2*pi*1*t1); %this represents a pause in the music

Below is the MATLAB sound() function set up so that it plays the notes in order for the Star Spangled Banner.

sound([G53,E54,C52,E5,G5,C62,p, ...
E63, D64,C62,E5,FS,G52,p, ...
G53,G53,E62,D63,C6,B62,p, ...
A63,B64,C62,C6,G5,E5,C52,p, ...
E5,G53,C52,E5,G5,C62,p, ...
E6,D63,C62,E5,FS,G52,p, ...
G5,G53,E62,D6,C6,B62,p, ...
A6,B63,C62,C6,G5,E5,C5,p, ...
E64,E64,E62,F6,G6,G62,p, ...
F64,E64,D62,E6,F6,F62,p, ...
F6,E62,D64,C6,B62,p, ...
A64,B64,C62,E5,FS,G52,p, ...
G5,C6,C6,C64,B64,A6,A6,A6,D6,F63,E6,D63,C62,B6,p, ...
G53,G53,C62,D63,E63,F63,G62,p, ...
C63,D63,E62,F6,D6,C6f]);

Alumni Liaison

Basic linear algebra uncovers and clarifies very important geometry and algebra.

Dr. Paul Garrett