Thursday, December 11, 2008

Logical Branching & Looping in MATLAB

Motion Control of a Rotational Stepper Motor,


1 Overview: Programming & Experiment Goals

This session is used to introduce basic (MATLAB) programming concepts, including

looping (”for” and ”while”)

logical conditions

further use of script M-files

The driving application is programmable motion control of a stepper motor. Specific tasks include

estimating the arc covered in a single step from imprecise measurements

a priori bounds over measurement and estimate uncertainties

open loop planned motion

retrieval of sensor data

feedback: closed loop control of planned motion

The Components & Equipment used in this experiment include:

A control box

A stepper motor on a mount

A flat flag, mounted on the motor shaft,

A protractor on the face of the mount, indicating the rotation angle of the flag

Two photo resistor cells, at the 0and 90positions

Two light emitting diodes (LEDs), mounted near the respective photo resistors

MATLAB software on a PC, including the Instrument Control & Data Acquisition Tool Boxes.

Experiments Outline The experiments involve a computer controlled rotational stepper motor. The motor receives two

types of commands from the computer (which are translated to voltage inputs in the control box):

1. A step command results with the shaft turning over a fixed arc length. The step arc length varies from motor to

motor, from a few degrees (you will determine how many) in this experiment, to a small fraction of a single degree,

in precision positioners.

2. A direction command, determining whether subsequent steps motions are executed in the clockwise or counterclockwise

directions.

The motor is also equipped with two photo-resistors, used as light sensors: when the photo-resistor is exposed to

light its resistance is lower than when it is covered. The computer is capable of obtaining sensor readings. Thus the computer

can tell whether themotor shaft is at the 0or the 90positions, since there the flag is covering the respective sensors.

The experimental tasks in Lab 2 include:

Estimating the single step angle: Since the flag does not provide a precise reading of the shaft’s rotation angle,

a single step experiment is insufficient. You will design a multi-step experiment to obtain an accurate estimate, as

well as an upper bound over the residual error. This type of experimental estimates of instrument properties and the

search for a priori error bounds are prevalent in engineering applications.

Open and Closed Loop Motion Planning: Motion planning is a principal ingredient in engineering applications

such as robotics and computer controlled machine tools (e.g., a programmable lathe). In open loop motion planning

one relies on machine precision and program the number of steps and direction changes that comprise the

desired path. In closed loop motion planning sensors are used to determine the motor position, to correct for the

accumulation of small errors in executed motion. Here you will utilize the available photosensors.

In order to be able to execute these tasks we shall have to employ the important programming tools of logical branching

and looping.

2 Homework Assignments

Pre-Lab Homework

Read this handout carefully.

Read Chapter 7 in the textbook

Optional: Read Section 4.2-4.3 (pp.87-93)

Do Problems 1, 5, 7(a), 10, 11, on pages 227 – 229; include printout of the MATLAB command window with

your answers.

Prepare an M-Files to perform all the tasks listed as Pre-Lab Programming, along this handout.

Pre-Lab Programming tasks include

_ Including a printout of your programs in the Pre-Lab Report that is submitted in the first session of the

lab, and

_ Bringing to the lab a floppy diskette that includes these programs. You will run the programs in the lab

and will not have enough time to prepare them in the lab.

Post-Lab report due one week after experiment is finished.

3

3 The Experiment

3.1 Computer-Controlled Stepper Motor Operation & Sensor Thresholds

The computer is connected to various instruments through input and output (I/O) ports. Those are used to receive information

from the stepper motor and related devices, and to issue commands to the motor, through its control box. Motion

actuation and data acquisition by use of MATLAB require some detailed MATLAB programs that are already stored as

M-Files in the lab computers. You do not need to access these detailed programs directly (nor should you attempt to

modify them!). For the purpose of our lab, it suffices to accept the name of each program as a MATLAB command. Once

you type the name of the program, it is executed to achieve the desired action. The following description concerns motion

actuation and related commands.

Important: On occasion you will need to rotate the stepper motor shaft manually. To be able to do so you have to first

switch the control box off. (Use the single on/off switch on the control box.) Remember to switch the control box ”on”

again when you finish such manual rotation!

The command setup rot initiates the necessary programs for interactions with the motor. You should issue this

command in the command window once in each session. (Repeated execution may result with memory problems!)

The command onerot executes the motion actuation signal. In our stepper motor it is a short signal of 5 Volts,

received at the control box step port. Each time onerot is executed, such an impulse is received and the motor rotates a

fixed angle, which we call a “step”. Motion over longer angles is achieved via a succession of steps.

The direction signal may take two possible voltage values: Following the execution of the command cwrot, a constant

10V signal is sent to the direction input port in the motor control box. Future actuation signals will then cause the motor

to rotate clockwise. Following the execution of the command ccrot, the direction port voltage is set to zero volts and

future actuation signals will cause the motor to rotate counterclockwise. The direction voltage is kept constant, until a

new command is issued, or until the system is disconnected. The commands cwrot and ccrot do not cause any motion

by themselves.

The function readcell(·) reads the voltage across the photo-resistors: readcell(1) reads sensor #1 and readcell(2)

reads sensor #2. You will have to determine, experimentally, which of the two sensors is #1 and which is #2.

EXAMPLE: To assign the sensor #1 reading to a MATLAB variable named sensor value one issues the MATLAB

command

sensor value=readcell(1);

Note Again: The commands setup rot, onerot, cwrot, ccrot and readcell(.) require special software

and are not recognized byMATLAB, other than on HTT&TL computers. To test programs using these and other HTT&TL

special command on other computers you have to comment these commands (using %) and substitute the by “dummy

display commands. For example, to debug a motion control program, temporarily replace “cwrot” by “disp(’next

motion clockwise’). However, the programs you prepare in your Pre-Lab assignment must contain the original

HTT&TL commands.

Experiment 1: Test the basic motor functions, using the command window.

1. Execute (once!) the command setup rot.

2. Type in the command window the for loop

for k=1:10

onerot;

end

4

Watch the motor while you hit the return key to execute the loop. You or your team mate may lightly touch the

shaft of the motor (NOT the flag!) whiel the program executes. Record your observation.

3. Type ccrot and repeat the previous step. Record your observation.

4. Type cwrot and repeat the previous step. Record your observation.

5. Switch off the control box; bring the flag to a position between the two sensors (say, at 45). Execute the functions

readcell(1) and readcell(2) and record in your notebook the returned values.

6. Repeat the previous step when the 0sensor is covered.

7. Repeat the previous step when the 90sensor is covered.

8. Based on the previous 3 experiments, determine

(a) What are the respective positions of sensor #1 and sensor #2

(b) Determine what you consider as a good threshold such that

readcell(1)>threshold implies that sensor #1 is covered

readcell(1)implies that sensor #1 is exposed

Is the same threshold good for sensor #2?

Pre-Lab Task 1. Consider the following program and explain in detail what should be the response of the motor

cwrot

while readcell(1)

onerot

end

Save this program in an M-file named move a while.m

Lab Experiment 2. The purpose of this experiment is to test your threshold and practice the use of while loops.

1. Switch the control box off, bring the flag near the 180position and switch the control box on again.

2. Type cwrot in the command window

3. Execute move a while.m

4. Repeat step 1, above, and type ccrot in the command window.

5. Execute move a while.m

6. Record your observations

3.2 Determination of A Single Step Size

The purpose of this experiment is to determine the angle (in degrees) travelled by the flag in a single step.

The Challenge: Since the flag is not pointed, angle reading includes an error of up to 2:

measured angle = real angle + error

Execution of a single step will thus yield

estimated step = measured terminal angle - measured initial angle

= real terminal angle + error2 - real initial angle - error1

5

and the total error may be up to twice the original error bound.

The Remedy: If instead of a single step, a succession of n steps is executed, the single step estimate becomes

estimated step = measured terminal angle - measured initial angle

n

= real terminal angle - real initial angle + error2 - error1

n

= real step size + error2 - error1

n

(1)

The advantage is the here the total measurement error (error1 - error2) does not increase, but its effect on the

estimated step is reduced by a factor of n.

Pre-Lab Task 2. Create a program named step angle estimate.m. This program should

1. Uses the input command (with a screen display of the request, see page 28-29 in the book) to request input values

for n and initial angle.

2. Executes a for loop that commands n counterclockwise steps (i.e., in the angle growth direction).

3. Uses the input command to request a value for terminal angle.

4. Uses Equation (1) to estimate the step angle, and assign it to a variable named step angle.

5. Uses either disp or fprintf command to display the estimated step angle.

Lab Experiment 3.

1. Visually estimate an upper bound (in degrees) over the measured angle error.

2. Using Equation (1), compute how many steps are needed (i.e. how large should n be) in order to guarantee that the

step estimation error will be less than 0.01.

3. Estimate the step angle:

(a) Estimate the current angle of the flag.

(b) Execute step angle estimate.m with n as determined in part 2.

(c) Input the values for n and initial angle.

(d) Watch the motor as your program executes, and count how many full rotations it completes before it stops.

(e) Estimate the terminal angle of the flag once the motor stops. Remember to add 360for each complete circle

(i.e., each time the flag passes the original angle)! For example, if the starting angle estimate is 36and the

flag completes two full circles and stops at 275, the ending angle is 2 × 360+ 275= 975.

(f) Input the value of terminal angle.

3.3 Open Loop Motion Planning

Here the goal is to make the motor go through a succession of pre-assigned angle motions, using for loops.

Pre-Lab Task 3. Create a program named open loop.m to perform the following tasks

1. Rotate clockwise an arc of1 70.

2. Display the statement Arc No. 1 Completed

1If the assigned arc length is not an integer multiple of a single step angle, round the necessary number of steps to the nearest integer. You may use

MATLAB’s round commnd (see MATLAB help).

6

3. Rotate counterclockwise 1435.

4. Display the statement Arc No. 2 Completed

5. Rotate clockwise 25.

6. Display the statement Mission Completed

Lab Experiment 4. Debug and execute the program open loop.m. Include a printout of the relevant portion of the

command window in your lab report.

3.4 Closed Loop Motion Planning

Here the goal is to make the motor go through a succession of pre-assigned angle motions, using sensor measurement

feedback and both for and while loops.

Pre-Lab Task 3. Create a program named closed loop.m to perform the following tasks

1. Uses the input command to obtain by user input the values of threshold, num0sensor = the number (1 or 2)

of the photo resistor at the 0position, and of num90sensor = the number (1 or 2) of the photo resistor at the 90

position. These variables will be used in using readcell(num...) and in logical conditions in what follows.

2. Rotate clockwise till the 0position is reached.

3. Display the statement Arc No. 1 Completed

4. Rotate counterclockwise till the 90position is reached.

5. Display the statement Arc No. 2 Completed

6. Continue an additional counterclockwise 425.

7. Display the statement Arc No. 3 Completed

8. Rotate clockwise till he 0position is reached.

9. Display the statement Mission Completed

Lab Experiment 5. Debug and execute the program closed loop.m. Include a printout of the relevant portion of the

command window in your lab report.

7

MATLAB programming concepts

This session is used to introduce basic (MATLAB) programming concepts, including

Variable definitions

Arrays and array manipulations

2D plotting

Script M-files

Basic (Engineering / Science) concepts, including

Parameter estimation from noisy data

Matching a mathematical model to data

The driving application involve estimation of the speed of sound in air 1 and acoustic distance measurement to remote

objects. Specific tasks include

Measuring the travel time between ultrasound transducers

Estimating the speed of sound in air from measurement data

Acoustic distance measurement

The components & equipment used in this experiment include

Two sound wave transducers: an emitter (essentially, a small, directional loudspeaker) and a receiver (essentially, a

directional microphone); a mark on the basis of each transducer assembly indicates which is the emitter and which

is the receiver.

The emitter is connected to a pre-programmed signal generator

Both transducers are connected to a digital oscilloscope

A measuring tape (metric), glued to the lab bench

A clip board

MATLAB, installed on the computer.

Experiment Outline: The emitter transducer emits a short burst of several cycles of a sound wave at a 40kHz frequency2.

The receiver, located at a selected distance from the emitter, picks up the sound wave. The two transducers are connected

to the two input channels of a digital oscilloscope. The process is automatically repeated, periodically, every 10 ms. 3

The oscilloscope displays the recorded sound waves from both transducers. Using features of the oscilloscope display

you will be able to measure the time it takes travel time of the sound wave from the emitter to the receiver. In principle, a

single measurement suffices to compute an estimate of the speed of sound:

speed of sound =

travel distance

travel time

(1)

or equivalently

travel distance = speed of sound · travel time (2)

1 Actually, the speed of sound varies with temperature and air pressure, and the results obtained will provide an estimate for the altitude and

temperature of our lab environment.

2The frequency of 1 Hz (one Hertz) means one cycle per second; 1 kHz (one kilo-Hertz) stands for 1000 cycles per second. Thus the sound wave

used in our experiments is of 40,000 cycles per second.

3The notation “ms” stands for “milisecond”, or 0.001 second. We shall later encounter also the “μs”, standing for “microsecond”, which is 1μs =

1 · 106 = 1e 6 sec.

2

In practice, multiple measurements are needed to overcome measurement errors of both the travel time and the distance

between the transducers. Moreover, due to the physical structures of the transducers, distance measurements will be

biased, meaning that even without any other inaccuracies, the actual distance between transducers is different from what

we can measure by a fixed amount:

measured travel distance = speed of sound · travel time + bias (3)

This last equation is of the general form of a linear graph

y = a x + b (4)

You will conduct ten experiments and obtain ten values for distance / travel time pairs. You will then use a MATLAB

program to optimally fit a linear graph of the form (4) to your data. The quantity “a” in that fit will be your estimate of

the speed of sound, as in (3).

Having estimated the speed of sound and the distance measurement bias, acoustic distance measurement to a remote

object will again use the formula (3): Now the two transducers will be placed side by side. The emitter’s sound wave will

travel to the target object, bounce back and be recorded by the receiver. The travel distance will thus be twice the distance

to the remote object. Having measured the travel time, we can thus conclude

distance to remote object = 0.5 (speed of sound · travel time + bias) (5)

The representation of the relationship between travel distance and travel time in the basic formula (3) is a mathematical

model. Your final task in this lab will be find an alternative mathematical model, relating the distance to the peak

amplitude of the return sound wave, instead of to the travel time.

Programming: The data recording and processing required in this experiment require an introduction to some of the

essential building blocks of programming, in any programming language. We shall use this lab as an opportunity to

introduce these concepts, as explained below.

2 Homework Assignment

¿From Lab 2 and on, our practice will be to go through relevant components of the text book before the lab meeting, and

include assigned preparatory work by then. Since this is our first meeting, the primer component of Lab 1 is included in

the work for the final lab report. In preparation of your report

Read this entire handout carefully.

Do the following in a Pre-Lab assignments

Read4 in the course text MATLAB: An Introduction with Applications

_ Chapter 1

_ Chapter 2

_ Optional Section 4.3.1 (pp. 91-93) (We shall discuss the necessary material in class)

_ Optional: 2D Plots, pp. 119-124 (We shall discuss the necessary material in class)

Do the following problems (include a printout of the MATLAB command window with the solution of each

problem):

_ Problems 1-5 and 1-15 on pages 28, 30

_ Problems 2-1, 2-3, 2-14 on pages 53, 54

Following completion of the Lab, write a Post-Lab report, summarizing the experiments and your findings, as explained

below.

4Here and throughout, preparatory reading is essential for the understanding of class material and the ability to perform tasks in class or in the lab.

3

3 Measuring The Speed of Sound: The Experiment

You will conduct ten experiments and record your data in your notebook. Later you will analyze these data using MATLAB.

Attention: Make sure you record all your measurements in the standard meters, seconds and Volts units!

1. Position the emitter so that its face will be directed along the measuring tape and the front of its base is flush with

the 0 position.

2. Position the receiver at a point of your selection along the measuring tape, anywhere between 5 - 50cm, facing the

emitter. (The position is measured from the front of the transducer’s base.)

The oscilloscope displays both the emitter signal (Channel 1) and the receiver signal (Channel 2). You will notice the

record of the short interval of a high amplitude emitter waveform, early on (on the left), followed by an essentially

(close to) zero reading and then, an area of increased amplitude waveform, more to the right. This second waveform

is the record of the sound wave sensed by the receiver.

3. Read the time it takes sound to travel from the emitter to the receiver:

(a) Press the curser bottom

(b) Under the display window, select t1

(c) Use the “entry” knob to bring one vertical cursor in the oscilloscope window to the point where, by your

visual judgement, the emitter burst begins

(d) Under the display window, select t2

(e) Use the “entry” knob to bring the second vertical cursor in the oscilloscope window to the beginning of the

elevation in the response, in Channel 2.

(f) The corresponding time difference - the sought travel time - appears as “_t” in the oscilloscope display

window. (Pay attention to the time units used: 1 ms = 1e-3 s; 1μs = 1e-6 s.)

4. Record the data pair, consisting of the sound travel time (in seconds!) and the distance between the fronts of the

bases of the two transducers (in meters!)

Using a calculator, estimate the speed of sound from each of the ten experiments, using the formula (1).

5. For later use, record also the peak-to-peak amplitude of the received sound wave

(a) Press the curser bottom

(b) Under the display window, select v1

(c) Use the “entry” knob to bring one horizontal cursor in the oscilloscope window to the lowest peak of the

receiver signal

(d) Under the display window, select v2

(e) Use the “entry” knob to bring the second horizontal cursor in the oscilloscope window to the highest peak of

the receiver signal

(f) The corresponding voltage difference appears as “_v” in the oscilloscope display window. (Pay attention to

the voltage units used! Record the peak-to-peak value in Volts.)

4

4 Acoustic Distance Measurement: The Experiment

Here we shall demonstrate the principles of commercially available acoustic distance measurement devices (with diverse

applications ranging from monitoring chemical process reactors to real estate), with our simple setup.

Place the standing clipboard at the zero position of the measuring tape, with its face facing the length of the measuring

tape.

Place both the receiver and the emitter, side by side, at a selected position along the measuring tape (5 - 30 cm),

facing the clipboard. (The front of their bases is used as the transducers’ position, just as in the previous experiment.)

Use the oscilloscope to measure the travel time of the sound wave from the emitter to the receiver. Record the

distance and travel time in your notebook.

Repeat the experiment 2 more times, at different distances.

In §5.6 you will compare the actual distance with a distance estimated in terms of the travel time.

5

5 Data AnalysisWith MATLAB

MATLAB basics will be learned, based on your assigned reading and class practice. §5.1 and §5.2 are included as

immediate reminders. The discussion of data analysis begins in §5.3.

5.1 Creating & Saving a New M-File on a Memory Stick

MATLAB computations can be executed directly from the MATLAB command window, or by use of program files.

MATLAB programs are saved as M-files in an accessible directory, as explained below. Since lab computers will be used

by others we shall never save programs on the hard disk. Here and throughout, programs will be saved as M-files on a

memory stick and run from the appropriate directory. In what follows we refer to the directory of the memory stick as

E”. Make sure to check which directory is actually occupied by the memory stick and substitute the correct reference for

“E”. Files saved on the hard disk might be erased and lost without prior notice!

Insert a memory clip

In the MATLAB command window, change directory to the floppy drive

>> cd E:\

Verify the current directory

>>pwd

>> E:\

Under “File”, select “New M-file”

Save the new M-file under a name of your choice, with the suffix “.m” (for example SOS Lab1.m is a good name

for a program used to measure the speed of sound in Lab 1). The following rules apply to names used for both

MATLAB variables and M-files:

the name must begin with a letter

the name may contain letters, numbers and the underscore sign

the name may not contain other characters, or a space

the name may not be equal to the name of a recognized MATLAB function (such as sin, cos, log, etc.).

When in doubt, do not use a suspected name for your variables and programs!

To run an M-file as a script program, type its name in the MATLAB workspace and hit return. Alternatively, select

the run icon in the editor window.

5.2 Defining MATLAB Variables

This part is covered in the required Lab 1 book reading and will be practiced in class. The following is are few highlights:

Variables are used to store data values. The name of the variable is a reference to a point in the memory.

MATLAB will not recognize a variable before it is expressly defined.

To see that type boom in the command window. Assuming a variable bum was not previously defined, the response

will be

>>boom

>>??? Undefined function or variable ’boom’.

6

The equal sign “=” is used in MATLAB, as in most programming languages, for the assignment operation, acting

from left to right. Thus

>>moom=5

assigns the value 5 to the variable moom. If moom did not previously exist, it also creates this variable in the

memory. Contrary to the usual usage of “=” in mathematics, the legal operation

>>moom=moom+1

assigns to the existing variable moom a new value, comprising its old value plus one.

By default, each value assignment command is followed by a display of the assigned value in the MATLAB command

window. This is mostly undesirable, and in case of large array, will dramatically slow down you programs!

To prevent this and as a matter of standard practice, end each assignment command with a semicolon “;”

Variables may be scalars (the default), taking a single number (or character) as a value. They may also be one, two

or three dimensional arrays of values. Details are provided in the book (pp. 40-48).

5.3 Experimental Data Recording and Plotting

The following commands should be included in an M-file used to record and plot the data from the speed of sound

experiment. Your Lab report should include the M-file and a printout of the MATLAB command window were the M-file

is executed5

define three row vectors of size 1 × 10 (remember to type a semicolon “;” at the end of each vector definition!):

A vector tdistance whose entries are the 10 distances between the two transducers in your experiments

A vector ttime whose entries are the corresponding measured travel times

A vector amplitude whose entries are the corresponding measured maximal peak-to-peak amplitudes of

the receiver signal

Create a 3 × 10 matrix named sosdata whose first row comprises the vector tdistance, the second row is the

vector ttime and the third row is amplitude.

Use the disp command to display the tabulated data in the matrix sosdata.

Include a command to discrete plot of the travel distance (vertical axis) as a function of the travel time (horizontal

axis), using black asterisks for data points

plot(ttime,tdistance,’k*’)

Following the plot command, include the title “Speed of Sound Data: <your team names>”, and axis titles “travel

time” and “travel distance”:

>>title(’Speed of Sound Data: ...’)

>>xlabel(’travel time’)

>>ylabel(’travel distance’)

Save and run theM-file. Your lab report will include the printedM-file and printed output of the final version of theM-file.

5The simplest way to print a portion of the command window is to use the mouse to highlight that section, then selecting Print Selection

under the File menu.

7

5.4 Polynomial Curve Fitting - General

Our goal here is to fit the data in the vectors tdistance and ttime with an equation of of the form (3):

tdistance = speed of sound · ttime + bias (6)

Referring to this form, we are trying to estimate the values of the coefficients a=speed of sound and b=bias of a

first order polynomial that best fit our recorded data. Here we shall use two MATLAB functions that are introduced only

much later in the book (search the index):

_ TheMATLAB function polyfit is used to fit data with a polynomial curve. We shall be interested in the spacial case of

a first order (linear) polynomial of the form (4)-(6). Following is a general description of polyfit and the way it is used:

Given same size vectors x=[x(1),...,x(N)] and y=[y(1),...,y(N)] and a prescribed polynomial order M,

the objective of polyfit is to find the polynomial

p(u) =

N

X

k=0

akuk (7)

that solves the approximation problem

min

a0,...,aM

N

X

l=1

(y(l) p(x(l)))2 (8)

That is, the graph of the polynomial p(u) has to best approximate the graph of the data pairs (x(k),y(k)) in the least

mean squares sense. The general syntax of polyfit is:

>>p=polyfit(x,y,M)

where, in the notations of (7), we identify “p” with the coefficients’ vector p = [aM, aM1, . . . , a1, a0].

_ The MATLAB function polyval is used to evaluate a polynomial v=p(u) at a point, or list of points x. The syntax

is

>>y=polyval(p,x)

where the interpretation of p = [aM, . . . , a1, a0] is as above, and where x is a single variable or an array. The returned

value(s) y=p(x) are stored in an array y whose size is the same size as that of x.

5.5 Linear Fitting of The Speed of Sound Experiment

As stated above, our goal is to fit the data pairs (ttime,tdistance) by a straight line, as in (6). You should therefore

include in your M-file the command

>>est=polyfit(ttime,tdistance,1)

In accordancewith the notations of (6), the returned vectorwill be the best estimate of est=[est(1),est(2)]=[speed

of sound, bias]. If we want to see how good this estimate is, we should substitute the estimated coefficients and

the entries of ttime in the right hand side of (3). This is done with the command

>>polyval(est,ttime)

For a visual comparison you will therefore include in your program a plot command that compares the raw data with the

linear estimate

8

>>plot(ttime,tdistance,’k*’,ttime,polyval(est,ttime))

Notice that here we allow a continuous plot of the linear approximation. Add a title (including name of team members)

and axes labels commands.

To evaluate the quality of your estimate of the speed of sound, search the web for “speed of sound” and compare your

estimate to what you find in the web. The site http://hyperphysics.phy-astr.gsu.edu/hbase/sound/souspe.html is one option.

5.6 Acoustic Distance Measurement

Here you will compute the estimated distance from the transducers to the clipboard in the experiments carried in §4. The

estimated distance is given by Equation 5, where you have to use your estimates of the speed of sound and the bias term.

That is, you have to use theMATLAB function polyval and the linear polynomial est=[est(1),est(2)]=[speed

of sound, bias]. In your report compare the distance estimate with the actual distance, as recorded in the experiment.

6 An Alternative model

As an alternative to the model (3), you will seek a representation of the distance as a function of the maximal peak-to-peak

amplitude of the receiver signal. We expect a reverse relation: the longer the distance, the smaller the amplitude. Therefore

the sought model will be a function of the variable x = 1

amplitude . You are allowed to use the polyfit function to test

polynomial approximations of the form

travel distance _

M

X

l=0

alxl (9)

with various levels of the degree M. At this point you may rely on visual inspection to evaluate the quality of the

approximation. Clearly, the higher the degree M you allow, the better the fit can be. However, we want the simplest

possible formula, and will stop increasing M if there is no noticeable improvement. The findings in your report should

include:

The values of the optimal coefficients and polynomial degree

A plot, comparing the discrete data pairs ttime,amplitude with the plot of the approximating function (9) that

you identified. The plot must include a title (with your name) and axes labels.

Hint: To create the data vector x = 1

amplitude from the data vector amplitude, you use the place-by-place vector

division command

>> x=1./amplitude;

If you expect the amplitude to vary with the distance according to a power law, (amplitude = constant _ distancen)

you can try another way to fit the data: Taking the logarithm of both sides of the equation above, you get the following

equation:

>>log (amplitude) = log (constant) + n log(distance)

If you then define new variables:

u=log(amplitude)

v=log(distance)

L=log(constant)

you get the equation:

u = L + n * v

9

This is a linear equation and you can do a least squares fit to the data to get he best fit value for n (the slope) and L (the

y-intercept). Using the data you took for amplitude vs. distance, use MATLAB to create the new variables u and v. Then

use polyfit to get the best fit values for the slope and y intercept. Finally, convert your results back to get the best fit

values for constant and n in the equation above: amplitude = constant _ distancen.

Question (answer in your lab report):

1. How does your best fit values for constant and n compare with the values from your Power Law fit in Excel?

2. How do you think that Excel gets its Power Law fit?

3. How could you use polyfit and a linear straight line fit to find the best fit values of yo and a from (x, y) data that fits

the following exponential equation:

y = y o * exp (a *x)

10

Search

My Blog List