Matlab and Vectors

Playing sound with Matlab should be as easy as doing some complicated algebra. In Matlab, a sound file is nothing else then a big vector that is then played on the sound card. If you are already familiar with the Matlab syntax for vectors you may hop to the next section.

To create a vector "a" type the following:

>> a = [1 2 3]

Matlab should then answer with:

a =

[ 1 2 3 ]

If you do not want that it replies to every of your commands, you can put a semicolon at the end of the line. Try generating a vector b now:

>> b = [1 2 3 4];

Now there is a variable "b". To show a list of all current variables type "whos":

>> whos

and Matlab will answer

Name Size Bytes Class

a 1x3 24 double array

b 1x4 32 double array

Grand total is 7 elements using 56 bytes

From the output you can see that vector a contains 3, and that vector b contains 4 elements.

Ok, that's all we need to know so far to be able to play sounds in Matlab.

Playing a Wave File

To play a sound file you may download the following: interwikiattachment:bothkind.wav. Click with the right mouse button on the link and choose "Save As". Place the file in a folder of your choice and then go to Matlab and change the "current directory" in the top toolbar to that directory.

To see which directory Matlab currently uses, type "pwd" (print working directory) or "cd" without any argument. If you had saved the file e.g. to "C:\Temp" then it would print

>> pwd

ans =

C:\Temp

To see if the wav file is really there, type "dir *.wav"

>> dir *.wav

ans =

bothkind.wav

Good! Now we tell Matlab to load the file into a vector. Make sure that you put the semicolon behind the command, otherwise Matlab would answer by printing out the whole sound file. Note: here we need read two parameters from the file. The music itself will be stored in a, and the variable "f" will contain the sampling frequency.

>> [a, f] = wavread('bothkind.wav');

You may check the size of the vector with the "whos" command and the sampling frequency

>> whos a

Name Size Bytes Class

a 84096x1 672768 double array

Grand total is 84096 elements using 672768 bytes

>> f

f =

11025

And now: Play the sound!

>> sound(a, f);

The next chapter "MatlabTrial?" would explain how to play a real country song with Matlab. :-)


Last edited on Friday, June 6, 2003 7:10:42 am.

Valid XHTML 1.0! Valid CSS!
Page Execution took 2.896 seconds