Title: Algorithms A Little MATLAB Programming
1AlgorithmsA Little MATLAB Programming
2Find at least one root of the following function
Methods
- Quadratic Formula (analytic)
- Factorization (analytic)
- Iteration (algorithmic)
3(No Transcript)
4When we solve problems, whether homework or
extensive programming assignments a plan of
action is needed.
Algorithm
Etymology alteration of Middle English
algorisme, from Old French Medieval Latin Old
French, from Medieval Latin algorismus, from
Arabic al-khuwArizmi, from al-KhwArizmI fl A.D.
825 Arabian mathematician A procedure for
solving a mathematical problem (as of finding the
greatest common divisor) in a finite number of
steps that frequently involves repetition of an
operation broadly a step-by-step procedure for
solving a problem or accomplishing some end
especially by a computer
5Structured Programs
Producing an algorithm for a particular
programming problem is a very personal task. Two
programmers can arrive equally valid solutions
using very different approaches. Fortunately
there are some programming/algorithm basic
techniques that have been shown to produce
efficient solutions. In 1968 Edgar Dijkstra
outlined a technique called structured
programming. He remarkable idea that algorithms
could be constructed from only four types of
structures.
6Sequences of instructions
7Branches
8Loops
9Modules
10Algorithm Building Structures
- Sequential Steps executed one after another in
a linear sequence. - Selection Allows for decision processes based
on conditional true/false tests. - Repetition Allows parts of algorithm to be
repeated. - Number based Steps repeated a specific number
of times - Condition based Steps repeated until a
true/false condition becomes false.
11Actually there are a few more things that are
needed to actually produce a working program that
implements an algorithm. These are the nuts and
bolts of any programming language and are
specific to that language
- Data
- Operations (add, subtract, compare etc.)
- Input/Output capability
12Suppose that we wish to calculate the interest
penalty added to an account after a payment is
made. There are several steps involved in the
solution
- Examine the problem to determine what information
the problem is requesting. This determines a
goal to be achieved. - Plan a strategy. Determine equations that are
needed in solution. Hierarchy charts can be
useful to prepare an overview of the solution. - Determine what information in the form of inputs
is necessary to effect a solution. Express these
inputs in general terms.
13A hierarchy chart is a useful tool for getting an
overview of how parts of an algorithm fit
together and interact
Interest Calculation
Get original balance, rate and payment
Calculate new balance
Output new balance
Apply payment to original balance
Calculate interest to be applied
Find new balance
14Once we have an overview of the problem it is
time to work on the algorithm. Algorithm can be
expressed in one of a couple of ways
Flowcharts
Pseudocode
15Flowcharts provide a graphical representation of
the algorithm. There are standard flowcharting
symbols that are normally used
16Pseudocode is a more natural language form of
algorithm expression
- Read Bal, Pay, Rate
- Subtract Pay from Bal
- Calculate Int Rate/12Bal
- Add Int to Bal
- Display Int, Bal
Many prefer this method of expression as the
pseudocode is usually quite similar to the final
program.
17The Matlab Code
bal input('Enter current balance ') pay
input('Enter payment ') rate input('Enter
annual interest rate ') bal bal - pay int
rate/100/12bal bal bal
int fprintf('\nInterest added\t7.2f\nNew
balance\t7.2f\n', ... int, bal)
18Population Density
Devise an algorithm to calculate the population
density of the Earth.
Pseudocode
- Enter radius of sphere
- Enter habitable fraction
- Enter population
- Calculate habitable surface area
- Divide population by habitable surface area
- Report population density
19How about some MATLAB?
20Matlab has the usual programming operators for
forming expressions
The multiplication, division and power operators
can be modified to perform element-by-element
arithmetic on vectors and matrices of matching
size.
21Calculated values are saved in computer memory.
In running programs memory locations are
internally referenced by storage location number.
Fortunately when we use a programming language
like MATLAB, we reference the memory locations by
names that usually describe the contents.
22MATLAB Variables
- Can contain letters, numbers and the underscore
character - Must begin with a letter
- Can be up to 31 characters long in all versions
of MATLAB and 63 characters in versions 6.5 and
greater - Names are case sensitive. Radius and radius are
different variables - Avoid using names of builtin functions, i.e. cos
sin, exp, sqrt, etc. Once a function name is
used as a variable name, the function can no
longer be used.
23The following are predefined when MATLAB is
started.
- ans a temporary variable that holds the value
of the last expression that was not assigned to a
variable - pi contains an accurate value of p
- eps the smallest difference between two numbers
that can be stored. About 2.2x10-16 - inf infinity
- i j sqrt( -1 )
- NaN Not a Number. Used when MATLAB cannot
determine a proper value. For instance 0/0
24Operators and Expressions
With the exception of the unary minus sign,
operators are binary operators. That is they act
on two operands. The unary minus changes the
sign of the the operand immediately following it.
Unary Operation -5 Binary Operation 53
Expressions are made up of series of operators
and operands.
A b 5.6 / 2
25When used in an extended sequence, operations are
executed in a certain order controlled by order
of precedence rules. Operations of equal
precedence are evaluated from left to right.
- Parentheses ()
- Transpose(')
- Power(, .)
- Unary plus (), unary minus (-), logical negation
() - Multiplication (, .), right division (/, . /),
left division (\, .\) - Addition (), subtraction (-)
- Colon operator ()
- Less than (lt), less than or equal to (lt),
greater than (gt), greater than or equal to (gt),
equal to (), not equal to () - Logical AND ()
- Logical OR ()
26Assignment Statements
The workhorse operation in sequential
processing is the assignment statement in which a
right-hand side expression is equated to a
left-hand side variable.
A A b 5.6 / 2
All quantities on the right-hand side must be
defined before evaluation. The result replaces
any previous value of the left side variable
The order of evaluation can be changed with
parentheses
A A (b 5.6) / 2
27Elementary Math Functions
Most all language have builtin functions which
calculate the basic elementary math functions
sin, exp, sqrt, etc.
See pp. 105-108 in Hahn and Valentine
28Input/Output
User input can be obtained via the input function
gtgt A input('Give me a number ') Give me a
number 5
Input can also process string responseses
gtgt A input('Give me a string ','s') Give me a
string Hello
29Simple output can be produced in one of two ways
Missing semi-colon
gtgt A 5 3 Produces no output
gtgt A 5 3 A 8
disp function
gtgt disp(A is ) disp( A ) A is 8
30The output methods on the previous slide do not
produce nicely formatted output.
gtgtfprintf(\nThe value of A is 7.3f\n, A) The
value of A is 8.000
The first argument is called the template. It
contains a mixture of text to be printed,
formatting characters, and output specifiers. \n
is a newline character. The 7.3f format
specifier tells fprintf to save seven columns to
print a floating point number (f) with three
decimal place precision. Another useful
specifier is ni which reserves n columns for
printing an integer (no decimal part). For every
specifier in the template, an extra argument is
normally required. These arguments are the
values to be printed.
See Moore 7.7.2
31For every specifier in the template, an extra
argument is normally required. These arguments
are the values to be printed.
A 1 3 5 2 4 6 A 1
3 5 2 4 6
fprintf(The value of A is\n) fprintf(3i
\t 5.3f\n,A)
32The previous example used only sequential
processing ( the steps were executed
one-after-another). A selection structure
results when the exact processing to be executed
depends on a condition.
Suppose that in our interest example we wish to
apply a different interest rate if the accrued
balance is above a certain level. This requires
a decision (selection) process.
33The flowchart
34Pseudocode
- Read Bal, Pay, HRate, LRate, Cut
- Subtract Pay from Bal
- If Bal Greater Than Cut
- Rate HRate
- Otherwise
- Rate LRate
- Calculate Int Rate/12Bal
- Add Int to Bal
- Display Int, Bal
35The Matlab Code
bal input('Enter current balance ') pay
input('Enter payment ') high input('Enter
high annual interest rate ') low
input('Enter low annual interest rate ') cut
input('Enter penalty balance ') bal bal -
pay if (bal gt cut) rate high else
rate low end int rate/100/12bal bal
bal int fprintf('\nInterest added\t7.2f\nNew
balance\t7.2f\n',... int, bal)
36Selection Structures
37Quadratic Formula Algorithm
When creating a computer algorithm to calculate
roots given a, b, and c we have to think a bit.
There are actually three different cases. Two
different roots, a single repeated root, or two
imaginary roots. We need to test which
calculation is appropriate for each case.
For this we need a new technique Selection
38Quadratic Formula
39And the MATLAB?
40For MATLAB selection structures we need know how
to make comparisons and construct logical tests.
The first thing to remember concerning MATLAB
logical values is that it has a simple rule for
true and false values.
MATLAB assigns a value of 0 to any false
comparison test and 1 to any true test.
Conversely, MATLAB considers any non-zero value
true (even negative numbers) and any identically
zero value false.
41Logical Tests
42Matlab has a group of operators that are used to
for logical tests. They are called relational
operators. These operators are used to construct
logical expressions which evaluate to either true
or false values.
43Examples
a 5.5 b 1.5 c -3
a b gt 6.5 b c gt a a 3b
true ( 1 )
false ( 0 )
true ( 1 )
44Logical operators are used to construct compound
logical expressions that are used to test the
state of several conditions at once.
The precedence for the logical operators with
respect to each other is
- not () has the highest precedence.
- and ()
- or ()
45Examples
a 5.5 b 1.5 c -3 k -4
true ( 1 )
a lt 10 a gt 5 abs( k ) gt 3 k lt b a b lt c b
1.5
true ( 1 )
true ( 1 )
46When used in an extended sequence, operations are
executed in a certain order controlled by order
of precedence rules. Operations of equal
precedence are evaluated from left to right.
- Parentheses ()
- Transpose(')
- Power(, .)
- Unary plus (), unary minus (-), logical negation
() - Multiplication (, .), right division (/, . /),
left division (\, .\) - Addition (), subtraction (-)
- Colon operator ()
- Less than (lt), less than or equal to (lt),
greater than (gt), greater than or equal to (gt),
equal to (), not equal to () - Logical AND ()
- Logical OR ()
47Pitfalls
How about the following 6 gt 5 gt 4 2 5 gt 4 a
5 2 3 1 4 a gt 2
48For the Curious
How do you use logicals with vectors and matrices?
a 5 2 3 1 4 loc find( agt2 ) t a( loc )
49The if Structure
function y if_simple( x ) y 0 if ( x gt 0 )
y x2 end
50The if-else Structure
if ( x gt 0 ) y x2 else y -x end
51Nested if Structures
function y if_else_if( x ) if ( x lt 0 ) y
-x else if ( x lt 1 ) y x2
else y 1 end end
52The if-elseif-else Structure
function y if_elseif( x ) if ( x lt 0 ) y
-x elseif ( x lt 1 ) y x2 else y
1 end
53The following statements are intended to alert a
user of dangerously high oral thermometer
readings in degrees Fahrenheit.
if ( temp lt 97.5 ) disp(Temperature below
normal) elseif ( temp gt 97.5 )
disp(Temperature normal) elseif ( temp gt 99.5
) disp(Temperature slightly high) elseif (
temp gt 103.0) disp(Temperature dangerously
high) end
54Corrected Version
if ( temp lt 97.5 ) disp(Temperature below
normal) elseif ( temp lt 99.5 )
disp(Temperature normal) elseif ( temp lt
103.0 ) disp(Temperature slightly
high) else disp(Temperature dangerously
high) end
55Switch Case Structure
The switch statement is used to select from a
number of exactly matching cases. In some ways
it can replace an if-eleseif-else structure but
its use is more limited. It is often used to
select from a set of menu choices.
If ( choice 1) do some item 1 stuff elseif
choice 2) do some item 2 stuff elseif (
choice 3 ) do dome item 3 stuff else
ask again end
Hahn, p. 68
56choice input(Choose a menu item) switch
choice case 1 fprintf(\ndo some item 1
stuff\n) case 2 fprintf(\ndo some item 2
stuff\n) case 3 fprintf(\ndo dome item 3
stuff\n) otherwise fprintf(\nnot a
choice\n) end
57Loop Structures
58Repetition
Suppose one wants to calculate the following
expression
The following could be written in MATLAB
y 0 y y 1/sqrt( 1 ) y y 1/sqrt( 2
) y y 1/sqrt( 3 ) etc.
59There are obvious problems with this approach
The program has to be rewritten each time a
different value of n is desired. As written the
algorithm only works for n 3. The same
statement is used over and over. Consider a
slightly different set of statements
y 0 i 1 y y 1/sqrt( i ) i 2 y y
1/sqrt( i ) i 3 y y 1/sqrt( i )
60The last set of statements suggest a new
programming structure repetition
61In Ancient Times we would write the following in
FORTRAN
program sumroot read(10) n 10
format( 5i ) y 0 i 1 20 y y
1/sqrt( i ) if i .LE. n i i
1 goto 20 end if print( 30 )
y 30 format(16H The Answer is ,7.3f) end
62And how about the MATLAB?
63MATLAB uses the for statement for number limited
repetition.
n input(What is n ) y 0 for i 1n y
y 1/sqrt( i ) end fprintf(The result is
f, y)
Note the assignment statement after the for.
The colon in the expression produces a range of
values (1 to n in increments of 1 in this
instance). The instructions in the loop will be
executed once for each element in the range of
values. In the ith execution of the loop the
value of i will be the ith element in the range.
64The Range Operator
vname mqn m is first element q is spacing
(if omitted 1 is assumed) n is the maximum last
element
gtgt z 128 z 1 3 5 7 gtgt x 17 x 1 2
3 4 5 6 7
65Another Simple Example
y 0 for x1 0.5 3 y y x end
This executes the statement 5 times where x is
successively set to 1, 1.5, 2, 2.5, 3 and gives a
final value of 10 for y.
66Conditional Repetition
Number limited repetition is fairly
straight-forward. In each case the number of
repetitions is known or can be calculated at
execution time. In some situations though the
number of repetitions will depend on some true
false condition being met. Think of emptying a
large container of water one spoonful of water at
a time. You probably cannot predict the number
of spoonfuls you will have to remove to empty the
tank beforehand. The algorithm will be to
remove a spoonful of water from the vessel until
the container is empty.
67A Historical Example
In 1685 Wallis published a book called Algebra,
in which he described a method devised by Newton
for solving equations. In slightly modified
form, this method was also published by Raphson
in 1690. This form is the one now commonly
called Newtons method or the Newton-Raphson
method. Newton himself discussed the method in
1669 and illustrated it with the following
equation
There is a root near x 2
68Newton Raphson Method
1
69The basis for Newtons method is that a guess is
made for the root of the non-linear
equation. Equation 1 is applied repeatedly until
the left hand side of the equation x(new) is the
same as the value input on the right hand side,
x(old).
The stopping criteria is the condition x(old)
x(new)
70(No Transcript)
71And now for the MATLAB
72Conditional repetition in MATLAB is implemented
with the while statement. The while statement
structure is as follows
while ( condition is true ) execute these
statements end
73The condition supplied to the while is any valid
MATLAB logical expression that evaluates as true
or false. The condition must be true for the
statements in the body of the while structure to
be executed at least one time. This is the
notion that the MATLAB pre-tests the condition. A
false condition will cause execution to proceed
with the statement following the end
statement. Note that some statement in the body
must cause the condition to become false at some
point. Otherwise, the statements will continue
to be repeated forever.
74Heres the previous example using conditional
repetition
function outinvsq( n ) out 0 i 0 while ( i
lt n ) i i 1 out out 1/sqrt( i ) end
Bad! Use a for instead of a while.
75The Newton-Raphson Example
a input('a ') b input('b ') c input('c
') d input('d ') x input('Guess Root
') error 1 Insures while loop will
start while ( error gt 1e-6 ) y ax3 bx2
cx d yp 3ax2 2bx c xnew x
- y/yp Newton's formula next statement
iskey to stopping execution abs function makes
sure error is positive error abs((x -
xnew)/xnew) x xnew end fprintf('\nThe root
is f\n', xnew)
76Modules (MATLAB Functions)
77The Newton example demonstrates an algorithm that
is important in Numerical Methods. That is the
solution to nonlinear equations. By writing a
stand-alone script we are able to create a solver
that solves a specific type of problem (3rd order
polynomials). However the use of a script that
asks the user for input and prints an answer is
not convenient for putting the algorithm to good
use. One would like a facility for consuming
the inputs (a,b,c,d,guess) and replacing them
with the computed result. Think of the
expression y sin( pi )1. This takes the
argument, pi, and replaces it with the result of
sin(pi), zero. A function can do this.
78Consider the following change to the Newton scipt.
function y newt(a,b,c,d,x) function
newt arguments a,b,c,d - coefficients of 3rd
order polynomial x - a guess for root of
polynomial error 1 Insures while loop will
start while ( error gt 1e-6 ) y ax3 bx2
cx d yp 3ax2 2bx c xnew x
- y/yp Newton's formula error abs((x -
xnew)/xnew) x xnew end y x
79Functions
- Stored in m-file. First line has special syntax
- function out_var function_name ( arg1, arg2, )
- This indicates that function will return the
value of a local variable named out_var in place
of the function call. - M-file containing the function fname must be
named fname.m - Any variables used in the function are local to
the function. Function does not have access to
variables defined outside the scope of the
function. When function dies all of its
variables cease to exist. - Input and output arguments are passed by value
not name. - Functions may invoke (call) other functions.
Even themselves. - Functions should operate silently. No input or
output statements. Functions are designed to
return numerical values.
80Scripts
- Group of Matlab commands that are executed in
sequence just as they were typed at command
prompt. - Stored in a file with an extension ending in .m
in a directory in the Matlab execution list
(path). Executed by typing filename without
extension. - Scripts must handle own input/output using
commands such as input, fprintf, disp. - Variables are defined globally. Any variables
that exist when execution is started can be used
in the script. Any variables created by script
exist when script dies. - Scripts can execute other scripts.
81Variables, Functions, Scripts?
When MATLAB encounters the following what happens?
y a b sin( 1 )
We expect that MATLAB looks up the current values
of a and b, evaluates the sine of 1 radian, and
performs the arithmetic. This is true in general
but what is the result of
sin( 1 ) 5 y a b sin( 1 )
82When MATLAB encounters a name in an expression it
uses the following recipe to interpret the name
- Checks if the name is a variable
- Looks in the current directory for a script
m-file or function m-file of that name - Look to see if name is a built-in function
- Looks in the MATLAB search path directories for
an m-file of that name.