ece lab

23
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 For MATLAB Labs this semester, you will need a number of programs/files that are not present in MATLAB. To obtain these files, you have to ask your instructor for a file copy. Discrete Signals Time base: t = [0.0 0.1 0.2 0.3] Signal data: 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. 1

Upload: azimylabs

Post on 19-Dec-2015

2 views

Category:

Documents


0 download

DESCRIPTION

Introduction of ECE laboratory

TRANSCRIPT

Page 1: ECE Lab

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

For MATLAB Labs this semester, you will need a number of programs/files that are not present in MATLAB. To obtain these files, you have to ask your instructor for a file copy.

Discrete Signals

Time base: t = [0.0 0.1 0.2 0.3]Signal data: 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 five-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]'

1

Page 2: ECE Lab

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)

What does this code show?The output is:

The output shows the evaluated values of X=sin(T), where T holds the vector data of t1, t2, and t3 , therefore a three-element sequence, in a column vector representation.

Sampling Signals

2

Page 3: ECE Lab

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-to-digital (A/D) converter. If the continuous signal, xa(t), is band limited, 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.

fs >2fM: Original signal and sampled signal have the same frequency.

3

Page 4: ECE Lab

fs <=2fM: Sampled signal is aliased to some other frequency depending on the sampling frequency.

Try:t = 0:0.001:2;xa = sin(2*pi*5*t);plot(t,xa)hold onfs = 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

Note that the function plot(ts,xs,'ro-') plots a red, solid (due to the '-') line, with a circle(due to the 'o') at each data point. You can do a 'help plot' at the command line to see other plot options.

Note that sometimes copy and paste does not work when you have asterisk. In which case you want to type in the actual command.

To run the above program, you can copy, paste it in your workspace. Or you can File –New -M-File. Copy and paste there. Save it in some directory. Now make sure the Command Window has that as the working directory. Type in the name of the file in the Command Window and it should run it.

Q1: What is the frequency of xs2? What does the hold function do?

The sinusoidal wave produced has a period of 0.4 since the frequency sample is set to 7.5 Hz , because frequency is the inverse of the period . T he frequency of xs2 is 2.5 Hz.

The hold function determines whether new graphics objects are added to the graph or replace objects in the graph. Specifically, hold on retains the current plot and certain axes properties so that subsequent graphing commands add to the existing graph , while hold off resets axes properties to their defaults before drawing new plots. H old off is the default .

4

Page 5: ECE Lab

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 isn't setup. 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))

Q2: What does the strips command do? (See 'help strips'.) What does the .* operator do?

Strips(x) plots vector x in horizontal strips of length 250. If x is a matrix, strips(x) plots each column of x. The left-most column (column 1) is the top horizontal strip. Strips(x,n) plots vector x in strips that are each n samples long. Strips(x,sd,fs) plots vector x in strips of duration sd seconds, given a sampling frequency of fs samples per second. Strips(x,sd,fs,scale) scales the vertical axes. If x is a matrix, strips(x,n) , strips(x,sd,fs) , and strips(x,sd,fs,scale) plot the different columns of x on the same strip plot. Strips ignores the imaginary part of complex-valued x.

The . * operator is called the pointwise product. It is used for matrix multiplication.

5

Page 6: ECE Lab

Signal Processing Tool

The Signal Processing Toolbox application, SPTool, provides a rich graphical environment for signal viewing, filter design, and spectral analysis.

You can use SPTool to analyze signals, design filters, analyze filters, filter 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 computer's audio hardware.

The Filter Designer is for designing or editing FIR and IIR digital filters. Note that the FDATool is the preferred GUI to use for filter designs. FDATool is discussed in later labs.

The Filter Viewer is for analyzing filter characteristics. The Spectrum Viewer is for spectral analysis.

Open SPTool by typing sptool at the command prompt.

Try:Sptool

Use the View function to look at the “train" signal,”FIRbp" filter, and “trainse"spectrum.

Importing a Signal

You can use SPTool to analyze signals, filters, or spectra that you create at the Matlab command line.

You do this by importing signals, filters, or spectra from the Matlab workspace into the SPTool workspace using the Import item under the File menu.

At the command line, do:

fs = 1000;ts = 0:1/fs:0.5;f = 250 + 240*sin(2*pi*ts);x = sin(2*pi*f.*ts);

6

Page 7: ECE Lab

Import these signals (f and x) into the SPTool and use the tool to examine them.

Q3: What are the icons to use for horizontal zoom? Try zooming in using the mouse.

- Zoom in X (horizontal axis)

- Zoom Out X (horizontal axis)

Signal Browser

The Signal Browser tool is an interactive signal exploration environment. It provides a graphical view of the signal object(s) currently selected in the Signals list of SPTool.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.

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 click OK.

Try changing the sampling rate of the imported signal.

7

Page 8: ECE Lab

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, sawtoothNonperiodic 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 functionsstep, 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)];

8

Page 9: ECE Lab

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])

SinusoidsSinusoid parameters

Amplitude, A Frequency, f Phase shift, Φ Vertical offset, B

The general form of a sine wave is

y = Asin(2πft+Φ) + B

Example: generate a sine wave given the following specifications: A = 5 f = 2 Hz Φ= pi/8 radians

t = linspace(0,1,1001);A = 5; = 2;p = pi/8;sinewave = A*sin(2*pi*f*t + p);plot(t, sinewave)

Try:edit sine_wave

sine_wave

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:

9

Page 10: ECE Lab

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:

10

Page 11: ECE Lab

x(t) = ej2πft= cos(2πft) + jsin(2πft) = cos(ωt) + jsin(ωt)

If t is measured in seconds, then f will have units of sec-1, 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 defined variables jor i with different values.Useful Matlab functions

real, imag, abs, angle

Try:editzsigzsig(5)

Q4. Look at both figures and describe what you see.

Figure 1 shows a circle with a radius of 5, where 5 lines of different colors extend from the origin to the circle. Figure 2 shows 5 sinusoidal waves of different colors with amplitude of 5.

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 f rom external programs and instrumentation.

In this lab, we concentrate on reading and writing data that has already been stored in external files.

11

Page 12: ECE Lab

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 file 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-files to read in data from any of the supported file formats.

Matlab also has a large selection of low-level file 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 file in memory, position itself within the file, read or write specific formatted data, and then close the file.

You will be needing files such as \stockdata.xls" and others for this and other Labs. They are contained in ML01.zip which you can ask your instructor:

Try:help fileformatshelp iofunjan = textread('all_temps.txt','%*u%u%*[^\n]','headerlines',4);[data text] = xlsread('stockdata.xls');plot(data(:,2))legend(textf1,3g)

Explain how the colon operator works in the preceding plot command.

The colon operator works as a vector creator.

I = importdata('eli.jpg');

12

Page 13: ECE Lab

image(I)

Search for the file “theme.wav" in your computer, by the following command at the command line: which theme.wav

Now you can import the wav file using uiimport: uiimport

Browse for:

theme.wav

and play it: soundsc(data,fs)

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 file (MAT-file)with a .mat extension. The file is placed in the current directory.

The load command reads variables from a MAT-file 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 savedoc loadt = 0:0.1:10;x1 = sin(t);x2 = sin(2*t);x3 = sin(3*t);save myvarsclearload myvars t x3

Note the list of variables in the workspace tab in the upper left of the Matlab window.

13

Page 14: ECE Lab

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);

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);

Random numbers from other distributions

Random numbers from other distributions can be generated using the uniform random number generator and knowledge of the distribution's 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

14

Page 15: ECE Lab

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 Cn = 0.1*randnsize(sw);swn = sw + n:

Try:edit noisyCnoisyCstrips(swn, .1,1e4)

Zoom in on the strips plot. (Note: you might have to cut and paste from the noisyCscriptto generate swn.)

Pseudorandomness

This number:

0.95012928514718

is the first number produced by the Matlab uniform random number generator with itsdefault settings. Start up Matlab, set format long, type rand, and you get the number.If all Matlab users, all around the world, all on different computers, keep getting this same number, is it really \random"? No, it isn't. Computers are deterministic machines and should not exhibit random behavior. If your computer doesn't access some external device, like a gamma ray counter or a clock, then it must really be computing pseudorandom numbers.

A working definition 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:

15

Page 16: ECE Lab

s = rand('state')

This returns a 35-element vector containing the current state.

To change the state of rand:

rand('state',s) Sets the state to s.rand('state',0) Resets the generator to its initial

state.rand('state', sum(100*clock)) Sets to a new state each

time.

Commands for randn are analogous.

Try:s = rand('state')format longrandrand('state',sum(100*clock))s = rand('state')format longrand

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 effective sampling rate of x by keeping every nth sample starting with the first 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 effective 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)

16

Page 17: ECE Lab

resamples the sequence in vector x at p/q times the original sampling rate, using a polyphase filter 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 filter. It filters the input sequence in both the forward and reverse directions to remove all phase distortion, effectively doubling the filter order.

Try:load mtlbsound(mtlb,Fs)mtlb4 = downsample(mtlb,4)mtlb8 = downsample(mtlb,8)sound(mtlb8,fs/8)

Q5. What are the sizes of mtlb, mtlb4, and mtlb8? (If sound doesn't 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')

The sizes are: for Mtlb is (4001, 1), mtlb4 is (1001, 1) and mtlb8 is (501, 1) .

Modulation and Demodulation

17

Page 18: ECE Lab

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 speci_ed modulation method. The syntax is

y = modulate(x,fc,fs,'method')

where: x is the message signal. fc is the carrier frequency. fs is the sampling frequency. method is a flag for the desired modulation method

(see table below).

18

Page 19: ECE Lab

The demodfunction performs demodulation, that is, it obtains the original message signal from the modulated signal. The syntax is:

x = demod(y,fs,fs,'method')

19

Page 20: ECE Lab

demod uses any of the methods shown for modulate. The signal x is attenuated relative toy because demodulation uses lowpass filtering.

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-file3. Import the signal into SPTool and view it. Listen to the signal.

20