Digital Sound & Music: Concepts, Applications, & Science, Chapter 2, last updated 6/25/2013

33

graph's Edit menu and then resetting the range of the horizontal axis. The second way is to type

an axis command like the following:

axis([0 0.1 -2 2]);

This displays only the first 1/10 of a second on the horizontal axis, with a range of 2 to 2 on the

vertical axis so you can see the shape of the wave better.

You can also ask for a plot of a subset of the points, as follows:

plot(t(1:1000),y(1:1000));

The above command plots only the first 1000 points from the sine function. Notice that the

length of the two arrays must be the same for the plot function, and that numbers representing

array indices must be positive integers. In general, if you have an array t of values and want to

look at only the

ith

to the

jth

values, use t(i:j).

An advantage of generating an array of sample values from the sine function is that with

that array, you actually can hear the sound. When you send the array to the wavplay or sound

function, you can verify that you've generated one second's worth of the frequency you wanted,

middle C. You do this with

wavplay(y, sr);

or

sound(y, sr);

The first parameter is an array of sound samples. The second parameter is the sampling rate,

which lets the system know how many samples to play per second.

MATLAB has other built-in functions for generating waves of special shapes. We'll go

back to using fplot for these. For example, we can generate square, sawtooth, and triangular

waves with the three commands given below:

fplot('square(t)',[0,10*pi,-1.5,1.5]);

Figure 2.35 Square wave

fplot('sawtooth(t)',[0,10*pi]);

0 5 10 15 20 25 30

-1.5

-1

-0.5

0

0.5

1

1.5