Sunteți pe pagina 1din 18

E E 2 7 5 Lab

January 15, 2012

LAB 1. Signals in Matlab


Introduction
This lab will describe how to use Matlab for some basic signal representation and manipulation: Creating and importing signals Sampling and resampling Signal visualization Modeling noise Modulation You will be needing to run some special programs for all the MATLAB Labs in EE289. Go to http://www.cems.uvm.edu/~mirchand/classes/EE275/2012/Software/ and download sg01 and sg02 and save it somewhere on your disc. When using Matlab, set a path to it, so that all functions in sg01 and sg02 are accessible.

Discrete Signals
Time base: Signal data: t = [0.0 0.1 0.2 0.3] x = [1.0 3.2 2.0 8.5]

The central data construct in Matlab is the numeric array, an ordered collection of real or complex numeric data with one or more dimensions. The basic data objects of signal processing (one-dimensional signals or sequences, multichannel signals, and two-dimensional signals) are all naturally suited to array representation. Matlab represents ordinary one-dimensional sampled data signals, or sequences, as vectors. Vectors are 1-by-n or n-by-1 arrays, where n is the number of samples in the sequence. One way to introduce a sequence into Matlab is to enter it as a list of elements at the command prompt. The statement x = [1 2 3 4 5]

creates a simple ve-element real sequence in a row vector. It can be converted to a column vector by taking the transpose: x = [1 2 3 4 5] Column vectors extend naturally to the multichannel case, where each channel is represented by a column of an array. Another method for creating vector data is to use the colon operator. Consider a 1-second signal sampled at 1000 Hz. An appropriate time vector would be t = 0:1e-3:1; where the colon operator creates a 1001-element row vector representing time from zero to one second in steps of one millisecond. You can also use linspace to create vector data: t = linspace(0,1,1e3); creates a vector of 1000 linearly spaced points between 0 and 1. Try: t1 = [0 .1 .2 .3]; t2 = 0:0.1:0.3; t3 = linspace(0, 0.3, 4); T = [t1 t2 t3]; X = sin(T) Q1: What does this code show?

Sampling Signals
Analog signal sources include electromagnetic, audio, sonar, biomedical and others. Analog signals must be sampled in order to be processed digitally. Sampling x(n) = xa (nTs ) x is a discrete signal sampled from the analog signal xa with a sample period of Ts and a sample frequency of Fs = 1/Ts . Try: Fs = 100; N = 1000; stoptime = 9.99;

t1 = (0:N-1)/Fs; t2 = 0:1/Fs:stoptime; x1 = sin(2*pi*2*t1); x2 = sin(2*pi*3*t2); plot(x1) figure, plot(x2) An alternative to creating signals is to use a toolbox function. A variety of toolbox functions generate waveforms . Each of them requires that you begin with a vector representing a time base. Some of these functions will be described later in this lab.

Aliasing
Digital signals are often derived by sampling a continuous-time signal with an analog-todigital (A/D) converter. If the continuous signal, xa (t), is bandlimited, meaning that it does not contain any frequencies higher than a maximum frequency fM , the Shannon sampling theorem says that it can be completely recovered from a set of samples if the sampling frequency fs is greater than two times the maximum frequency of the signal to be sampled: fs > 2fM This maximum frequency fM is known as the Nyquist frequency. If the sampling frequency is not greater than two times the Nyquist frequency, the continuous signal cannot be uniquely recovered and aliasing occurs. You heard examples of aliased signals in homework number 1. fs > 2fM : Original signal and sampled signal have the same frequency. fs 2fM : Sampled signal is aliased to half the original frequency. Try: t = 0:0.001:2; xa = sin(2*pi*5*t); plot(t,xa) hold on fs = 15; ts = 0:1/fs:2; xs1 = sin(2*pi*5*ts); plot(ts,xs1,ro-) fs = 7.5; ts = 0:1/fs:2; xs2 = sin(2*pi*5*ts); plot(ts,xs2,ro-)

hold off Q2: What is the frequency of xs2? (That is, were you to reconstruct the signal, what frequency would you see?) You have to think about this one. (Note: you can use the GUI sptool, import the signal, set the sampling frequency to 7.5 and do a t; that will show you the answer). Q2A. What does the hold function do?

Signal Visualization
View signal amplitude vs. time index Functions: plot, stem, stairs, strips Listen to data: sound Note: the sound and soundsc commands will not work if your computer hardware isnt set up. If that is the case, view the signals instead of listening to them. Try: t = [0.1 0.2 0.3 0.4]; x = [1.0 8.0 4.5 9.7]; plot(t,x) figure, stem(t,x) figure, stairs(t,x) fs = 1000; ts = 0:1/fs:2; f = 250 + 240*sin(2*pi*ts); x = sin(2*pi*f.*ts); strips(x,0.25,fs) sound(x,fs) plot(ts,x) plot(ts(1:200),x(1:200)) Q3: What does the strips command do? (Type help strips on the command line.) Q4: What does the .* operator do in the equation for x above? (In Matlab, go to Help Product Help; then search for vector multiplication).

Signal Processing Tool


The Signal Processing Toolbox application, SPTool, provides a rich graphical environment for signal viewing, lter design, and spectral analysis. You can use SPTool to analyze signals, design lters, analyze lters, lter signals, and analyze signal spectra. You can accomplish these tasks using four GUIs that you access from within SPTool:

The Signal Browser is for analyzing signals. You can also play portions of signals using your computers audio hardware. Using the Signal Browser you can View and compare vector/array signals Zoom in on a range of signal data to examine it more closely Measure a variety of characteristics of signal data Play signal data on audio hardware To open/activate the Signal Browser for the SPTool, Click one or more signals (use the Shift key for multiple selections) in the Signals list of SPTool. Click the View button in the Signals list of SPTool. The Filter Designer is for designing or editing FIR and IIR digital lters. Note that the FDATool is the preferred GUI to use for lter designs. FDATool is discussed in later labs. The Filter Viewer is for analyzing lter characteristics. The Spectrum Viewer is for spectral analysis. Open SPTool by typing sptool at the command prompt >>. Try: >>sptool You see 3 panes - Signals, Filters Spectra. View all the signals in these panes. You can play the signals in Signals through using the speaker icon in the Signals browser. (Note: The speaker will only play the signal between the two cursors on the Signal Browser). When viewing spectra, note that many methods of determining spectra, including FFT are available. At this point, just use the FFT. In the Filters pane just View all three lters (LSip, PZip, FIRbp) at this time and get a sense of the capabilities of Filters.

Importing a Signal
You can use SPTool to analyze the signals, lters, or spectra that you create at the Matlab command line. You can import signals, lters, or spectra from the Matlab workspace into the SPTool workspace using the Import item under the File menu. Try: fs = 1000; ts = 0:1/fs:0.5; f = 250 + 240*sin(2*pi*ts); x = sin(2*pi*f.*ts); Import these signals (f and x) into the SPTool and use the tool to examine them. Q5: Explain in one sentence the signal x that you are generating. Q6: What are the icons to use for horizontal zoom and unzoom? Try zooming and unzooming using the mouse.

Changing Sample Rates


To change the sample rate of a signal in SPTool, 1. Click a signal in the Signals list in SPTool. 2. Select the Sampling frequency item in the Edit menu. 3. Enter the desired sampling frequency and cliick OK. That is all there is to it.

Try changing the sampling rate of the imported signal. You can play it and see the dierence in the sound.

Signal Generation
Signals Create a time base vector t = [0:0.1:2];

Create a signal as a function of time x = sin(pi*t/2); plot(t,x) Useful Matlab functions Nonperiodic functions ones, zeros Periodic functions sin, cos, square, sawtooth Nonperiodic Signals t = linspace(0,1,11) Step: y = ones(1,11); stem(y) Impulse: y = [1 zeros(1,10)]; stem(y) Ramp: y = 2*t; plot(y) Useful Matlab functions step, impulse, gensig Try: Step function: fs = 10; ts = [0:1/fs:5 5:1/fs:10]; x = [zeros(1,51) ones(1,51)]; stairs(ts,x) Impulse function with width w:

fs = 10; w = 0.1; ts = [-1:1/fs:-w 0 w:1/fs:1]; x = [zeros(1,10) 1 zeros(1,10)]; plot(ts,x) Delta function: ts = 0:0.5:5; x = [1 zeros(1,length(ts)-1)]; stem(ts,x) axis([-1 6 0 2]) Sinusoids Sinusoid parameters Amplitude, A Frequency, f Phase shift, Vertical oset, B The general form of a sine wave is y = Asin(2f t + ) + B Example: generate a sine wave given the following specications: A=5 f = 2 Hz = /8 radians t = linspace(0,1,1001); A = 5; f = 2; p = pi/8; sinewave = A*sin(2*pi*f*t + p); plot(t, sinewave) You can also edit a Matlab .m le that is in your path. Try: edit sine_wave sine_wave

The rst command lets you look at the program. The second command runs the program. You can also try: edit sinfun [A T] = sinfun(1,2,3,4)

Square Waves
Square wave generation is like sine wave generation, but you specify a duty cycle, which is the percentage of the time over one period that the amplitude is high. Example: duty cycle is 50% (the Matlab default) frequency is 4 Hz. t = linspace(0,1,1001); sqw1 = square(2*pi*4*t); plot(t,sqw1) axis([-0.1 1.1 -1.1 1.1]) Example: duty cycle is 75% frequency is 4 Hz. t = linspace(0,1,1001); sqw2 = square(2*pi*4*t,75); plot(t,sqw2) axis([-0.1 1.1 -1.1 1.1])

Sawtooth Waves
Sawtooth waves are like square waves except that instead of specifying a duty cycle, you specify the location of the peak of the sawtooth. Example: peak at the end of the period (the Matlab default) frequency is 3 Hz.

t = linspace(0,1,1001); saw1 = sawtooth(2*pi*3*t); plot(t,saw1) Example: peak is halfway through the period frequency is 3 Hz. t = linspace(0,1,1001); saw2 = sawtooth(2*pi*3*t,1/2); plot(t,saw2)

Complex Signals
Periodic signals can be represented by complex exponentials: x(t) = ej 2f t = cos(2f t) + jsin(2f t) = cos(t) + jsin(t) If t is measured in seconds, then f will have units of sec1 , and will have units of radians/second. In signal processing, we associate the unit circle with one sampling cycle, so that a sampling frequency of Fs is associated with 2 radians, and the Nyquist frequency Fs /2 is associated with radians. Values of in the upper half-plane, in units of Hz, then correspond to frequencies within the sampled signal. In Matlab, type: x = exp(2*pi*j*f*t); plot(x) Matlab recognizes either j or i as the square root of -1, unless you have dened variables j or i with dierent values. Useful Matlab functions real, imag, abs, angle Try: edit zsig zsig(5)

Look at both gures and describe what you see.

Importing Data
An important component of the Matlab environment is the ability to read and write data from/to external sources. Matlab has extensive capabilities for interfacing directly with data from external programs and instrumentation. In this lab, we concentrate on reading and writing data that has already been stored in external les. Files come in a variety of standard formats, and Matlab has specialized routines for working with each of them. To see a list of supported le formats, type: help fileformats To see a list of associated I/O functions, type: help iofun Matlab provides a graphical user interface, the Import Wizard, to the various I/O functions. You access the Wizard by choosing File Import Data or by typing: uiimport The Matlab command importdata is a programmatic version of the Wizard, accepting all of the default choices without opening the graphical user interface. You can use importdata in M-les to read in data from any of the supported le formats. Matlab also has a large selection of low-level le I/O functions, modeled after those in the C programming language. These allow you to work with unsupported formats by instructing Matlab to open a le in memory, position itself within the le, read or write specic formatted data, and then close the le. Try: You can skip the next 12 lines

jan = textread(all_temps.txt,%*u%u%*[^\n],headerlines,4); [data text] = xlsread(stockdata.xls); plot(data(:,2))

legend(text{1,3}) Explain how the colon operator works in the preceding plot command. I = importdata(eli.jpg); image(I) which theme.wav uiimport Browse for: theme.wav soundsc(data,fs) Replace the above 12 lines with the following: Use uiimport to import eli.jpg and theme.wav. Look at the image and play the sound.

Save and Load


Two data I/O functions are especially useful when working with Matlab variables. The save command writes workspace variables to a binary Matlab data le (MAT-le) with a .mat extension. The le is placed in the current directory. The load command reads variables from a MAT-le back into the Matlab workspace. Although quite specialized, save and load can be used for day-to-day management of your Matlab computations. Try: doc save doc load t = 0:0.1:10; x1 = sin(t); x2 = sin(2*t); x3 = sin(3*t);

save myvars clear load myvars t x3 Note the list of variables in the workspace tab in the upper left of the Matlab window.

Modeling Noise
To model signals in space, in the atmosphere, in sea water, or in any communications channel, it is necessary to model noise. Matlab has two functions for generating random numbers, which can be added to signals to model noise. Uniform random numbers A = rand(m,n); generates an mxn array of random numbers from the uniform distribution on the interval [0,1]. To generate uniformly distributed random numbers from the interval [a,b], shift and stretch: A = a + (b-a)*rand(m,n); Specically: un=-5 + rand(1,1e6); hist(un,100); Gaussian random numbers A = randn(m,n); generates an mxn array of random numbers from the standard normal distribution with mean 0 and standard deviation 1. To generate random numbers from a normal distribution with mean mu and standard deviation sigma, shift and stretch: A = mu + sigma*rand(m,n); Specically: un=10 + 5*randn(1,1e6); hist(un,100);

Random numbers from other distributions Random numbers from other distributions can be generated using the uniform random number generator and knowledge of the distributions inverse cumulative distribution function. Random number generators for several dozen common distributions are available in the Statistics Toolbox.

Adding Noise to a Signal


noisy signal = signal + noise y1 = x + rand(size(x)) % uniform noise y2 = x + randn(size(x)) % Gaussian noise Example: Add Gaussian noise to middle C. fs = 1e4; t = 0:1/fs:5; sw = sin(2*pi*262.62*t); % middle C n = 0.1*randnsize(sw); swn = sw + n: Try: edit noisyC noisyC strips(swn, .1,1e4) Zoom in on the strips plot. (Note: you might have to cut and paste from the noisyC script to generate swn.)

Pseudorandomness
This number: 0.95012928514718 is the rst number produced by the Matlab uniform random number generator with its default settings. Start up Matlab, set format long, type rand, and you get the number. If all Matlab users, all around the world, all on dierent computers, keep getting this same

number, is it really random? No, it isnt. Computers are deterministic machines and should not exhibit random behavior. If your computer doesnt access some external device, like a gamma ray counter or a clock, then it must really be computing pseudorandom numbers. A working denition of randomness was given in 1951 by Berkeley professor D. H. Lehmer, a pioneer in computing and, especially, computational number theory: A random sequence is a vague notion ... in which each term is unpredictable to the uninitiated and whose digits pass a certain number of tests traditional with statisticians ... Random number generators proceed deterministically from their current state. To view the current state of rand, type: s = rand(state) This returns a 35-element vector containing the current state. To change the state of rand: rand(state,s) rand(state,0) rand(state, sum(100*clock)) Commands for randn are analogous. Try: s = rand(state) format long rand rand(state,sum(100*clock)) s = rand(state) format long rand Sets the state to s. Resets the generator to its initial state. Sets to a new state each time.

Resampling
The Signal Processing Toolbox provides a number of functions that resample a signal at a higher or lower rate.

y = downsample(x,n) decreases the eective sampling rate of x by keeping every nth sample starting with the rst sample. x can be a vector or a matrix. If x is a matrix, each column is considered a separate sequence. y = upsample(x,n) increases the eective sampling rate of x by inserting n 1 zeros between samples. x can be a vector or a matrix. If x is a matrix, each column is considered a separate sequence. The upsampled y has x n samples. y = resample(x,p,q) resamples the sequence in vector x at p/q times the original sampling rate, using a polyphase lter implementation. p and q must be positive integers. The length of y is equal to ceil(length(x) p/q ). If x is a matrix, resample works down the columns of x. y = interp(x,r) increases the sampling rate of x by a factor of r. The interpolated vector y is r times longer than the original input x. y = decimate(x,r) reduces the sampling rate of x by a factor of r. The decimated vector y is r times shorter in length than the input vector x. By default, decimate employs an eighth-order lowpass Chebyshev Type I lter. It lters the input sequence in both the forward and reverse directions to remove all phase distortion, eectively doubling the lter order. Try: load mtlb sound(mtlb,Fs) mtlb4 = downsample(mtlb,4) mtlb8 = downsample(mtlb,8) sound(mtlb8,fs/8) What are the sizes of mtlb, mtlb4, and mtlb8? (If sound doesnt work, plot the signals.) t = 0:0.00025:1; x = sin(2*pi*30*t) + sin(2*pi*60*t); y = decimate(x,4); subplot(211), stem(x(1:120)) axis([0 120 -2 2]) title(Original Signal) subplot(212), stem(y(1:30))

title(Decimated Signal)

Modulation and Demodulation


Modulation varies the amplitude, phase, or frequency of a carrier signal with reference to a message signal. The Matlab modulate function modulates a message signal with a specied modulation method. The syntax is y = modulate(x,fc,fs,method) where: x is the message signal. f c is the carrier frequency. f s is the sampling frequency. method is a ag for the desired modulation method (see table below). M ethod Description amdsb-sc or am Amplitude modulation, double side-band, suppressed carrier amdsb-tc Amplitude modulation, double side-band, transmitted carrier amssb Amplitude modulation, single side-band fm Frequency modulation pm Phase modulation ppm Pulse position modulation pwm Pulse width modulation qam Quadrature amplitude modulation The demod function performs demodulation, that is, it obtains the original message signal from the modulated signal. The syntax is: x = demod(y,fs,fs,method) demod uses any of the methods shown for modulate. The signal x is attenuated relative to y because demodulation uses lowpass ltering.

Exercise: High and Low


1. Create a signal equal to the sum of two sine waves with the following characteristics: 3-second duration

Sampling frequency = 2 kHz Sinusoid 1: frequency 50 Hz (low), amplitude 10, phase = 0 Sinusoid 2: frequency 950 Hz (high), amplitude 1, phase = 0 2. View and listen to the signal using an M-le 3. Import the signal into SPTool and view it. Listen to the signal.

HAND IN ANSWERS TO ALL QUESTIONS STARTING WITH THE LETTER Q IN FRONT OF IT.
(Contribution from Paul Beliveau for helping put this material together is acknowledged. The material derives principally from the MathWorks training document MATLAB for Signal Processing, 2006.)

c 2012GM

S-ar putea să vă placă și