Programming with MATLAB - PowerPoint PPT Presentation

1 / 85
About This Presentation
Title:

Programming with MATLAB

Description:

Algorithm: an ordered sequence of precisely defined instructions that performs ... Very good use of find() in Projectile function example see notes!!! 4-35. More? ... – PowerPoint PPT presentation

Number of Views:88
Avg rating:3.0/5.0
Slides: 86
Provided by: icc48
Category:

less

Transcript and Presenter's Notes

Title: Programming with MATLAB


1
Chapter 4 Programming with MATLAB
2
4-2
Algorithms and Control Structures Algorithm an
ordered sequence of precisely defined
instructions that performs some task in a finite
amount of time. Ordered means that the
instructions can be numbered, but an algorithm
must have the ability to alter the order of its
instructions using a control structure. There
are three categories of algorithmic
operations Sequential operations Instructions
executed in order. Conditional operations
Control structures that first ask a question to
be answered with a true/false answer and then
select the next instruction based on the
answer. Iterative operations (loops) Control
structures that repeat the execution of a block
of instructions.
3
4-3
Structured Programming A technique for designing
programs in which a hierarchy of modules is used,
each having a single entry and a single exit
point, and in which control is passed downward
through the structure without unconditional
branches to higher levels of the structure. NO
go to statements!!! In MATLAB these modules
can be built-in or user-defined functions.
4
Advantages of structured programming
  • 1. Structured programs are easier to write
    because the programmer can study the overall
    problem first and then deal with the details
    later.
  • 2. Modules (functions) written for one
    application can be used for other applications
    (reusable code).
  • 3. Structured programs are easier to debug
    because each module is designed to perform just
    one task and thus it can be tested separately
    from the other modules.

(continued )
4-4
5
Advantages of structured programming (continued)
  • 4. Structured programming is effective in a
    teamwork environment because several people can
    work on a common program, each person developing
    one or more modules.
  • 5. Structured programs are easier to understand
    and modify, especially if meaningful names are
    chosen for the modules and if the documentation
    clearly identifies the modules task.

4-5
More? See pages 184-185
6
Steps for developing a computer
solutionTop-down design (skip!!!)
  • 1. State the problem concisely.
  • 2. Specify the data to be used by the program.
  • This is the input.
  • 3. Specify the information to be generated by the
    program. This is the output.
  • 4. Work through the solution steps by hand or
    with a calculator use a simpler set of data if
    necessary.

(continued )
4-6
7
Steps for developing a computer solution
(continued)
  • 5. Write and run the program.
  • 6. Check the output of the program with your hand
    solution.
  • 7. Run the program with your input data and
    perform a reality check on the output.
  • 8. If you will use the program as a general tool
    in the future, test it by running it for a range
    of reasonable data values perform a reality
    check on the results.

4-7
8
Effective documentation can be accomplished with
the use of
  • 1. Proper selection of variable names to reflect
    the quantities they represent. (easy to forget
    what you did)
  • 2. Use of comments within the program.
  • 3. Use of structure charts.
  • 4. Use of flowcharts.
  • 5. A verbal description of the program, often in
    pseudocode.

4-8
9
4-9
Documenting with Charts Two types of charts
aid in developing structured programs and in
documenting them. These are structure charts
and flowcharts. A structure chart is a graphical
description showing how the different parts of
the program are connected together.
10
4-10
Structure chart of a game program. Figure 4.11
11
4-11
Flowcharts are useful for developing and
documenting programs that contain conditional
statements, because they can display the various
paths (called branches) that a program can
take, depending on how the conditional statements
are executed.
12
4-12
Flowchart representation of the if
statement. Figure 4.12
13
4-13
Documenting with Pseudocode We can document with
pseudocode, in which natural language and
mathematical expressions are used to construct
statements that look like computer statements but
without detailed syntax. Each pseudocode
instruction may be numbered, but should be
unambiguous and computable.
More? See pages 185-190.
14
4-14
  • Finding Bugs
  • Debugging a program is the process of finding and
    removing the bugs, or errors, in a program.
  • http//en.wikipedia.org/wiki/Computer_bugs
    (Grace Hopper)
  • Such errors usually fall into one of the
    following categories
  • Syntax errors such as omitting a parenthesis or
    comma, or spelling a command name incorrectly.
    MATLAB usually detects the more obvious errors
    and displays a message describing the error and
    its location.
  • 2. Errors due to an incorrect mathematical
    procedure. These are called runtime errors
    calculation errors.
  • Matlab does not care!!! Have to find yourself.

15
4-15
  • To locate a runtime error, try the following
  • Always test your program with a simple version of
    the problem, whose answers can be checked by hand
    calculations.
  • Display any intermediate calculations by removing
    semicolons at the end of statements.
  • To test user-defined functions, try commenting
    out the function line and running the file as a
    script.
  • 4. Use the debugging features of the
    Editor/Debugger, which is discussed in Section
    4.7.

(continued )
16
4-17
  • Development of Large Programs
  • Writing and testing of individual modules (the
    unit-testing phase).
  • Writing of the top-level program that uses the
    modules (the build phase).
  • Not all modules are included in the initial
    testing.
  • As the build proceeds, more modules are
    included.

(continued )
17
4-18
Development of Large Programs (continued)
  • Testing of the first complete program (the alpha
    release phase).
  • This is usually done only in-house by
    technical people closely involved with the
    program development.
  • There might be several alpha releases as
    bugs are discovered and removed.
  • Testing of the final alpha release by in-house
    personnel and by familiar and trusted outside
    users, who often must sign a confidentiality
    agreement.
  • This is the beta release phase, and there
    might be several beta releases.
  • In Class 4.1.2 p 241

18
4-19
Relational operators Table 4.21
Operator Meaning
lt Less than. lt Less than or equal
to. gt Greater than. gt Greater than or equal
to. Equal to Not equal to. 0 false 1
-- true x 3gt2 get 1 y 23 get 0
19
4-20
For example, suppose that x 6, 2,3
and y 4, 8,3. The following MATLAB
session shows some examples comparing element
by element. gtgtz (x lt y) z 0 1 0 gtgtz
(x y) z 1 1 0 gtgtz (x gt 5) z 1
0 0
20
4-21
The relational operators can be used for array
addressing. For example, with x 6, 2,3 and
y 4, 8,3. z
x(xlty) finds all the elements in x that are less
than the corresponding elements in y. The
result is z 2 (at position 2).
21
4-22
The arithmetic operators , -, , /, and \ have
precedence over the relational operators. Thus
the statement z 3 gt 1 4 is equivalent
to z 3 gt(14) more clear, preferable
and returns the result z 0. Can be used in if
statement if ( x gt (x1x2)/2 )
else end The relational operators
have equal precedence and Matlab evaluates them
left to right. Example x 3 lt 4 2 is
equivalent to x (3 lt 4) 2 ? 1 2 giving 1
22
4-23
The logical Class When the relational operators
are used, such as x (2 3 ) they create a
logical variable, in this case, x. Prior to
MATLAB 6.5 logical was an attribute of any
numeric data type. Now logical is a first-class
data type and a MATLAB class, and so logical is
now equivalent to other first-class types such as
character and cell arrays. Logical variables
may have only the values 1 (true) and 0 (false).
23
4-24
Just because an array contains only 0s and 1s,
however, it is NOT necessarily a logical array.
For example, in the following session k and w
appear the same, but k is a logical array and w
is a numeric array, and thus an error message is
issued. gtgtx -22 k (abs(x)gt1) x -2
-1 2 k 1 0 0 0 1 gtgtz x(k)
chooses elements of x where k 0 z -2
2 gtgtw 1,0,0,0,1 v x(w) ??? Subscript
indices must either be real positive... integers
or logicals. -- Quite confusing, since these are
integers.
More? See pages 192-193.
24
The logical function
  • Logical arrays can be created with the relational
    and logical operators and with logical function.
  • It returns array that can be used for logical
    indexing and tests.
  • B logical(A) returns logical array
    corresponding to numerical array A.
  • For example, we can correct previous subsection
    error by
  • w logical(1,0,0,0,1) v x(w)
  • When a finite real value other than 0 and 1 is
    assigned to a logical variable, it is converted
    to logical 1 and a warning is issued.
  • gtgt logical(3.2)
  • ans 1
  • Conversely, to convert logical to real use
    double()
  • gtgt z 7gt4
  • z 1
  • gtgt double(z)
  • ans 1
  • In addition, many arithmetic operations convert a
    logical array into a double array
  • gtgt x 1 3 gt 2 1
  • x 0 1
  • gtgt x x 0 produce numeric
    array by adding 0
  • x 0 1

25
Accessing Arrays Using Logical Arrays When a
logical array is used to address another array,
it extracts from that array the elements in the
locations where the logical array has 1s. So
typing A(B), where B is a logical array of the
same size as A, returns the values of A at the
indices where B is 1.
(continued )
4-25
26
Accessing Arrays Using Logical Arrays
(continued) Specifying array subscripts with
logical arrays extracts the elements that
correspond to the true (1) elements in the
logical array. Given A 4, 4, 6 5,
5, 8 61,14, 7 and B
logical(eye(3)), we can extract the diagonal
elements of A by typing C A(B) to obtain C
457. NOTE that B is defined as logical, not
just B eye(3) which would produce error
4-26
More? See page 194.
27
Logical operators element by element on
arrays With the exception of NOT (), they all
have lower precedence than arithmetic and
relational operators
Operator Name Definition NOT A returns an
array the same dimension as A the new array
has ones where A is zero and zeros where A is
nonzero. AND A B returns an array the same
dimension as A and B the new array has ones
where both A and B have nonzero elements and
zeros where either A or B is zero. OR A B
returns an array the same dimension as A and B
the new array has ones where at least one
element in A or B is nonzero and zeros where
A and B are both zero. XOR A B returns an
array the same dimension as A and B the new
array has ones where at elements in A and B are
opposite and zeros where A and B are same.
4-27
Truth Tables for scalars p and q not, and, or,
an xor. Class Ch4 11
28
  • Examples
  • gtgt x 2 0 4
  • x 2 0 4
  • gtgt y 2 -3 5
  • y 2 -3 5
  • gtgt z x
  • z 0 1 0
  • gtgt u x gt y ? (x) gt y
  • u 0 1 0
  • gtgt v ( x gt y ) ? x lt y, not xlt y
  • v 1 0 1
  • And (), or ( ), xor compare arrays of the same
    dimension, except it can also be compared to a
    scalar.
  • 2 1 gives 1, 0 1 gives 0, 0 0 gives 0,
    etc...
  • gtgt 3 0 0 -1 2 3 0 1 gives 1 0 0
    1
  • 2 1 gives 1, 0 1 gives 1, 0 0 gives 0,
    etc...
  • gtgt 3 0 0 -1 2 3 0 1 gives 1 1 0
    1
  • xor(2, 1) gives 0, xor(0,1) gives 1, xor(0,0)
    gives 0, etc...
  • gtgtxor( 3 0 0 -1, 2 3 0 1) gives 0 1
    0 0

gtgt x 2 4 7 gtgt y 3 2 7 gtgt a -1 4
9 gtgt z (xgty) a 0 1 0 a z 0
1 0 gtgt z (xgty) (xgta) 0 1 0 1 0
0 z 1 1 0 NOTE cannot write 1 lt
x lt 4 in Matlab Must use (1ltx) (xlt4)
29
Short circuit operators work on scalars
only. They evaluate their second operand only
when the result is NOT fully determined by the
first operand. Operator Name Definition Short
-Circuit AND Operator for scalar logical
expressions. A B returns true if both A and
B evaluate to true, and false if they do not. If
A is 0, then the whole expression must be 0 and
the 2nd operand is NOT evaluated Short-Circuit
OR Operator for scalar logical expressions. A
B returns true if either A or B or both
evaluate to true, and false if they do not. If A
is 1, then the whole expression must be 1 and the
2nd operand is NOT evaluated
4-28
30
Order of precedence for operator types. Table
4.32
Precedence Operator type First Parentheses
evaluated starting with the innermost
pair. Second Arithmetic operators and logical
NOT () evaluated from left to
right. Third Relational operators evaluated
from left to right. Fourth Logical
AND. Fifth Logical OR.
4-29
31
Logical functions Table 4.34
Logical function Definition all(x) Returns a
scalar, which is 1 if all the elements in the
vector x are nonzero and 0
otherwise. all(A) Returns a row vector having
the same number of columns as the matrix A
and containing ones and zeros, depending on
whether or not the corresponding column of
A has all nonzero elements. any(x) Retu
rns a scalar, which is 1 if any of the elements
in the vector x is nonzero and 0
otherwise. any(A) Returns a row vector having
the same number of columns as A and
containing ones and zeros, depending on whether
or not the corresponding column of the
matrix A contains any nonzero
elements. finite(A) Returns an array of the
same dimension as A with ones where the
elements of A are finite and zeros elsewhere.
(continued )
4-30
32
Table 4.34 (continued)
Logical function Definition ischar(A) Returns
a 1 if A is a character array and 0
otherwise. isempty(A) Returns a 1 if A is an
empty matrix and 0 otherwise. isinf(A)
Returns an array of the same dimension
as A, with ones where A has inf and zeros
elsewhere. isnan(A) Returns an array of the
same dimension as A with ones
where A has NaN and zeros elsewhere.
(NaN stands for not a number, which
means an undefined result.)
(continued )
4-31
33
Table 4.34 (continued)
  • isnumeric(A) Returns a 1 if A is a numeric array
    and 0 otherwise.
  • isreal(A) Returns a 1 if A has no elements with
    imaginary parts and 0 otherwise.
  • logical(A) Converts the elements of the array A
    into logical values.
  • xor(A,B) Returns an array the same dimension as
    A and B the new array has ones where either
    or B is nonzero, but not both, and zeros where
    A and B are either both nonzero or both zero.

4-32
34
The find Function
  • Computes an array containing the indices of the
    nonzero elements of the array A.
  • Computes the arrays u and v containing the row
    and column indices of the nonzero elements of the
    array A and computes the array w containing the
    values of the nonzero elements.
  • The array w may be omitted.
  • find(A)
  • u,v,w find(A)

4-33
35
Logical Operators and the find Function find(A)
-- computes an array containing the indices of
the nonzero elements of the array A Consider the
session gtgtx 3, 6, 0, 0, 1 gtgty 4, -2, 1,
1, 3 gtgtz find(xy) xy1 1 0 0 1- both
nonzero z 1 2 5 Note that the find
function returns the indices, not the values.
(continued )
4-34
36
Logical Operators and the find Function
(continued) In the following session, note the
difference between the result obtained by y(xy)
and the result obtained by find(xy) in the
previous slide. gtgtx 3, 6, 0, 0, 1 gtgty
4, -2, 1, 1, 3 gtgtvalues y(xy) y-values
where xy nonzero from before xy1 1 0 0 1
values 4 -2 3 gtgthow_many
length(values) how_many 3 Very good use of
find() in Projectile function example see
notes!!!
4-35
More? See pages 198-199.
37
The if Statement The if statements basic form
is if logical expression Note, no braces
like in C statements end z 0 w
0 if ( (x gt 0) (y lt 0) ) z log(x) w
sqrt(-y) end Every if statement must have an
accompanying end statement. The end statement
marks the end of the statements that are to be
executed if the logical expression is true.
4-36
More? See pages 201-202.
38
4-37
The else Statement The basic structure for the
use of the else statement is if logical
expression statement group 1 else statement
group 2 end
More? See pages 202-205.
39
4-38
Flowchart of the else structure. Figure 4.42
if ( x gt 0 ) x is scalar, (xgt0) is logical
disp(x is positive) else disp(x is not
positive) end
40
When the test, if logical expression, is
performed, where the logical expression may be an
array, the test returns a value of true only if
all the elements of the logical expression are
true!
4-39
41
For example, if we fail to recognize how the test
works, the following statements do not perform
the way we might expect. x 4,-9,25
Better to test scalar expressions!!! if x lt
0 -- Not all elements of x are negative,
so this branch is NOT
followed disp(Some elements of x are
negative.) else y sqrt(x) end Because the
test if x lt 0 is false, when this program is run
it gives the result y 2 0 3.000i 5
get complex root
4-40
42
Instead, consider what happens if we test for x
positive. x 4,-9,25 if x gt 0 y
sqrt(x) else disp(Some elements of x are
negative.) end When executed, it produces the
following message Some elements of x are
negative. The test if x lt 0 is false, and the
test if x gt 0 also returns a false value because
x gt 0 returns the vector 1,0,1.
4-41
43
NOTE that the following statements if ( x gt 0 )
if ( y gt 0 ) nested if statement statement
s end end can be replaced with the more concise
program if ( xgt0 ygt0 ) statements end
4-42
44
The elseif Statement The general form of the if
statement is if logical expression 1
statement group 1 elseif logical expression 2
statement group 2 elseif logical expression 3
statement group 3 else statement group
4 end The else and elseif statements may be
omitted if not required. However, if both are
used, the else statement must come after the
elseif statement to take care of all conditions
that might be unaccounted for.
4-43
45
4-44
Flowchart for the general if-elseif-else
structure. Figure 4.43
46
Example Assume marks is an array of students
test scores
avg mean(marks) dev std(marks) for j
1length(marks) if ( marks(j) gt avg dev )
grade(j) A elseif ( marks(j) gt avg
-dev ) grade(j) B else
grade(j) C end end
4-45
47
4-46
Flowchart illustrating nested if
statements. Figure 4.44
if x gt 10 y log(x) if ( y gt3 ) z
4y elseif ( y gt 2.5 ) z 2y else
z 0 end else y 5x z 7x end
In Class Ch4 17
48
Checking the number of Input and Output Arguments
  • Oftentimes need a function to act differently
    depending on how many inputs it gets.
  • Use nargin number of input arguments
  • function z f(x,y)
  • if (nargin 1 )
  • z log(abs(x))
  • elseif ( nargin 2)
  • z log(abs(xy))
  • else
  • disp(error)
  • end
  • Analogously, nargout gives you the number of
    output arguments

49
Strings A string is a variable that contains
characters. Strings are useful for creating
input prompts and messages and for storing and
operating on data such as names and
addresses. To create a string variable, enclose
the characters in single quotes. For example,
the string variable name is created as
follows gtgtname Leslie Simpson name
Leslie Simpson
(continued )
4-47
50
4-48
Strings (continued) The following string,
number, is not the same as the variable number
created by typing number 123. gtgtnumber
123 number 123 Strings are stored in row
vectors, in which each column represents a
character. number 1 row and 3 columns. Can
access any column by index name(5) gives letter
i Colon operator can be used name(8end) gives
the last name Simpson Can manipulate columns as
we do vectors for example to insert a middle
initial letter fullname name(16), A.,
name(7end) fullname(8) D change it to
D Can use findstr to find locations of certain
characters. findstr(fullname,i) get locations
5 and 12
Leslie Simpson
Leslie D. Simpson
51
  • Strings (continued)
  • Two strings are equal if and only if (iff) all
    the characters are equal (including blank
    spaces).
  • Matlab distinguishes between lower and upper
    cases.
  • Can use strcmp() to compare strings returns 1
    or 0
  • Can use lower() and upper() functions

52
Strings and the input Statement The prompt
program on the next slide uses the isempty(x)
function, which returns 1 if the array x is empty
and 0 otherwise. It also uses the input
function, whose syntax is x input(prompt,
s) This function displays the string prompt on
the screen, waits for input from the keyboard,
and returns the entered value in the string
variable x. The function returns an empty matrix
if you press the Enter key without typing
anything.
4-49
53
Strings and Conditional Statements The
following prompt program is a script file that
allows the user to answer Yes by typing either Y
or y or by pressing the Enter key. Any other
response is treated as the answer No. response
input(Want to continue? Y/N Y ,s) if
(isempty(response)(responseY)(responsey)
) response Y else response N end
4-50
More? See pages 209-210.
54
for Loops A simple example of a for loop is for
k 51035 x k2 end The loop variable k is
initially assigned the value 5, and x is
calculated from x k2. Each successive pass
through the loop increments k by 10 and
calculates x until k exceeds 35. Thus k takes
on the values 5, 15, 25, and 35, and x takes on
the values 25, 225, 625, and 1225. The program
then continues to execute any statements
following the end statement.
4-51
55
4-52
Flowchart of a for Loop. Figure 4.51 Typical
structure of the loop for loop variable
msn statements end Each for statement needs
the accompanying end statement. The statements
are executed once during each pass using the
current value of the loop variable
56
Note the following rules when using for loops
with the loop variable expression k msn
  • The step value s may be negative.
  • Example k 11-35 produces k 11, 8, 5.
  • If s is omitted, the step value defaults to 1.
  • If s is positive, the loop will not be executed
    if m is greater than n.
  • If s is negative, the loop will not be executed
    if m is less than n.
  • If m equals n, the loop will be executed only
    once.
  • If the step value s is not an integer, round-off
    errors can cause the loop to execute a different
    number of passes than intended. Be very
    careful!!!
  • When the loop is completed, k retains its last
    value.
  • Never alter value of the loop variable k within
    the statements
  • Reassign complex i if you plan to use it with
    loop indices i and j.

4-53
57
  • We may nest loops with conditional statements and
    with other loops.
  • Example
  • Create a matrix with 1s in 1st row and column
    and with other elements which are sums of two
    elements above and to the left if the sum lt 20,
    otherwise max.
  • function A specmatrix(n)
  • A ones(n)
  • for r 1n
  • for c 1n
  • if ( r gt 1 c gt 1 )
  • s A(r-1,c) A(r,c-1)
  • if s lt 20
  • A(r,c) s
  • else
  • A(r,c) max(A(r-1,c),A(r,c-1))
  • end
  • end
  • end
  • end

58
The break and continue Statements break
terminates the loop, but does not stop the
program for k 17 x 10-k3 if x lt
0 break end y(k) log10(x) end Usually
possible to write the code which avoids break
using while loop.
More? pp 210-217.
4-54
59
  • continue passes control to the next iteration
    of the loop, skipping any remaining statements in
    the body of the loop.
  • In the nested loops, continue passes control to
    the next iteration of the outer loop.
  • The following code uses a continue statement to
    avoid computing the logarithm of a negative
    number.
  • x 10,1000,-10,100
  • y NaNx
  • for k 1length(x)
  • if x(k) lt 0
  • continue
  • end
  • y(k) log10(x(k))
  • end
  • y
  • The result is y 1, 3, NaN, 2.

60
  • Using Array as a loop index
  • Can use matrices to specify the number of passes
    through the loop.
  • x 1 3 -2 4
  • for k x will go through 4 elements in the
    array x
  • y k2
  • end
  • A 1 3
  • -2 4
  • for V A will go through matrix A column
    by column
  • y v.2
  • end
  • y 1
  • 4
  • y 9
  • 16
  • Ex Compute the distance from 0 to a set of pts
    given by columns for a matrix
  • k 0

61
  • Implied Loops
  • All Matlab commands acting on arrays imply loops
  • x linspace(-1,4,100)
  • y sin(x).2 . exp(-x)
  • find (ygt0)
  • Each line above requires a loop in most other
    languages!!!
  • Also in Matlab, array operations work much, much
    faster than loops

62
Use of a Mask We can often avoid the use of
loops and branching and thus create faster (but
not always simpler) programs by using a logical
array as a mask that selects elements of another
array. Any elements not selected will remain
unchanged. The following session creates the
logical array C from the numeric array A given
previously. gtgtA 0 -1 4 9 -14 25
-34 49 64 gtgtC (A gt 0) The result is
4-55
63
We can use this mask technique to compute the
square root of only those elements of A given in
the previous program that are no less than 0 and
add 50 to those elements that are negative. The
program is A 0, -1, 4 9, -14, 25 -34, 49,
64 C (A gt 0) A(C) sqrt(A(C)) A(C)
A(C) 50 Rocket example 4.5-2 interesting,
but a bit hard and long.
4-56
More? See pages 217-218.
64
while Loops The while loop is used when the
looping process terminates because a specified
condition is satisfied, and thus the number of
passes is NOT known in advance. A simple
example of a while loop is x 3
initialization while x lt 31 disp(x)
loop body x 3x 1 update just before
the end of the loop end to be
checked by loop condition immediately The
results displayed by the disp statement are 3,
10, and 31.
4-57
65
  • The typical structure of a while loop follows.
  • while logical expression
  • statements
  • end
  • For the while loop to function properly, the
    following two conditions must occur
  • The loop variable must have a value before the
    while statement is executed initialization.
  • The loop variable must be changed somehow by the
    statements.
  • Also NEVER compare two real numbers for equality
  • if ( xy) , while ( x y ) instead use
    while( abs (x - y)lt eps )
  • The statements are executed once during each pass
    using the current value of the loop variable.
  • The looping continues until the logical
    expression is false.
  • Each while statement must be matched by end.

4-58
66
4-59
Flowchart of the while loop. Figure 4.53
67
4-60
68
Bisection Algorithm
4-61
69
The switch Structure The switch structure
provides an alternative to using the if, elseif,
and else commands. Anything programmed using
switch can also be programmed using if
structures. However, for some applications the
switch structure is more readable than code using
the if structure.
4-62
70
Syntax of the switch structure
  • switch input expression (which can be a scalar
    or string).
  • case value1
  • statement group 1
  • case value2
  • statement group 2
  • .
  • .
  • .
  • otherwise
  • statement group n
  • end

Note Compared to many other languages, Matlab
switch does NOT need a separate break statement
after each group. Only one value is possibly
matched and then control jumps to 1st statement
after the end!!!
4-63
71
The following switch block displays the point on
the compass that corresponds to that
angle. switch angle case 45
disp(Northeast) case 135 disp(Southeast)
case 225 disp(Southwest) case 315
disp(Northwest) otherwise disp(Direction
Unknown) end In class Ch4 35
4-64
More? See pages 225-227.
72
The switch statement can handle multiple
conditions in a single case statement by
enclosing case value in a cell array switch
angle case 0,360 disp(North) case
-180,180 disp(South) case -270,90
disp(East) case -90,270
disp(West) otherwise disp(Direction
Unknown) end In class Ch4 35
73
  • String variable in input expression can help
    readability
  • t linspace(0,3,100)
  • x cos(t).2 . exp(-t.2)
  • response input(Type min, max, or sum,s)
  • response lower(response)
  • switch response
  • case min
  • minimum min(x)
  • case max
  • maximum max(x)
  • case sum
  • total sum(x)
  • otherwise
  • disp(entered wrong choice)
  • end

74
The Editor/Debugger containing two programs to be
analyzed. Figure 4.71 Study those pages! Very
important for debugging large programs
4-65
More? See pages 228-234.
75
The remaining slides show figures from Chapter 4
and its homework problems.
4-66
76
4-67
Duration above 50,000 ft as a function of the
burn time. Figure 4.52
77
4-68
The state transition diagram for the college
enrollment model. Figure 4.81
78
4-69
Class enrollments versus time. Figure 4.82
79
4-70
Figure P19
80
4-71
Figure P24
81
4-72
Figure P25
82
4-73
Figure P29
83
4-74
Figure P30
84
4-75
Figure P31
85
4-76
Figure P32
Write a Comment
User Comments (0)
About PowerShow.com