Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Programming with MATLAB. Algorithms and Control Structures Algorithm: an ordered sequence of precisely defined instructions that performs some.

Similar presentations


Presentation on theme: "Chapter 4 Programming with MATLAB. Algorithms and Control Structures Algorithm: an ordered sequence of precisely defined instructions that performs some."— Presentation transcript:

1 Chapter 4 Programming with MATLAB

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. 4-2

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-3

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 module’s task. 4-5More? See pages 184-185

6 Steps for developing a computer solution: Top-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 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. 4-9

10 Structure chart of a game program. Figure 4.1–1 4-10

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. 4-11

12 Flowchart representation of the if statement. Figure 4.1–2 4-12

13 Documenting with Pseudocode - optional 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. 4-13More? See pages 185-190.

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)http://en.wikipedia.org/wiki/Computer_bugs Such errors usually fall into one of the following categories: 1.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. 4-14

15 To locate a runtime error, try the following: 1.If possible, test your program with a simple version of the problem, whose answers can be checked by hand calculations. 2.Display any intermediate calculations by removing semicolons at the end of statements. 3.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. 4-15 (continued …)

16 Development of Large Programs - optional 1.Writing and testing of individual modules (the unit- testing phase). 2.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. 4-17 (continued …)

17 3.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. 4.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 4-18 Development of Large Programs (continued)

18 Relational operators Table 4.2–1 Operator Meaning < Less than. <= Less than or equal to. > Greater than. >= Greater than or equal to. == Equal to ~= Not equal to. 0 – false 1 - true x = 3>2 get 1 y = 2==3 get 0 4-19

19 For example, suppose that x = [6, 2,3] and y = [4, 8,3]. The following MATLAB session shows some examples – comparing element by element. >>z = (x < y) z = 0 1 0 >>z = (x ~= y) z = 1 1 0 >>z = (x > 5) z = 1 0 0 4-20

20 The relational operators can be used for array addressing. For example, with x = [6, 2,3] and y = [4, 8,3]. z = x(x<y) finds all the elements in x that are less than the corresponding elements in y. The result is z = 2 (at position 2). 4-21

21 The arithmetic operators +, -, *, /, and \ have precedence over the relational operators. Thus the statement z = 3 > 1 + 4 is equivalent to z = 3 >(1+4) % more clear, preferable and returns the result z = 0. Can be used in if statement: if ( x > (x1+x2)/2 ) …… else …… end The relational operators have equal precedence and Matlab evaluates them left to right. Example: x = 3 < 4 ~= 2 is equivalent to x = (3 < 4) ~= 2  1~= 2 giving 1 4-22

22 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). 4-23

23 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. >>x = [-2:2]; k = (abs(x)>1) % x = -2 -1… 2 k = 1 0 0 0 1 >>z = x(k) % chooses elements of x where k ~=0 z = -2 2 >>w = [1,0,0,0,1]; v = x(w) ??? Subscript indices must either be real positive... integers or logicals. -- Quite confusing, since they all look like integers. 4-24More? 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. >> logical(3.2) ans = 1 Conversely, to convert logical to real use double() >> z = 7>4 z = 1 >> double(z) ans = 1 In addition, many arithmetic operations convert a logical array into a double array >> x = [ 1 3 ] > [2 1] x = 0 1 >> x = x + 0 % produce numeric array by adding 0 x = 0 1 Note that some functions line sin, cos, … are NOT defined on logicals – makes sense!

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. 4-25 (continued …)

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 = [4;5;7]. NOTE that B is defined as logical, not just B = eye(3) – which would produce an error 4-26More? See page 194.

27 OperatorNameDefinition ~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. &ANDA & 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. |ORA | 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 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 Logical operators – element by element on arrays With the exception of NOT (~), they all have lower precedence than arithmetic and relational operators Truth Tables for scalars p and q: not, and, or, an xor.

28 Examples: >> x = [ 2 0 4] x = 2 0 4 >> y = [ 2 -3 5] y = 2 -3 5 >> z = ~x z = 0 1 0 >> u = ~x > y  (~x) > y u = 0 1 0 >> v = ~( x > y ) %  x > v = ~( x > y ) %  x <= y, not x< 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... >> [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... >> [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... >>xor( [3 0 0 -1], [ 2 3 0 1]) gives 0 1 0 0 Use operator precedence 3&1+4  3&(1+4) gives 1 3|1-1  3|(1-1) gives 1 ~2==3 | 2==9  ((~2)==3) | (2==9) gives 0 >> x = [ 2 4 7] >> y = [ 3 2 7] >> a = [ -1 4 9] >> z = (x>y) & a % [0 1 0 ] & [ -1 4 9] z = 0 1 0 >> z = (x>y) | (x>a) % [0 1 0 ] | [1 0 0] z = 1 1 0 NOTE : cannot write 1 < x < 4 in Matlab Must use: (1<x) & (x<4)

29 PrecedenceOperator type FirstParentheses; evaluated starting with the innermost pair. SecondArithmetic operators and logical NOT (~); evaluated from left to right. ThirdRelational operators; evaluated from left to right. FourthLogical AND. FifthLogical OR. 4-29 Order of precedence for operator types. Table 4.3–2

30 Logical functionDefinition 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) Returns 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. 4-30 Logical functions: Table 4.3–4 (continued …)

31 Logical functionDefinition 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.) Table 4.3–4 (continued)4-31 (continued …)

32 Table 4.3–4 (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

33 The find Function find(A) [u,v,w] = find(A) 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. 4-33

34 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 >>x = [3, 6, 0, 0, 1]; >>y = [4, -2, 1, 1, 3]; >>z = find(x&y) % x&y=[1 1 0 0 1]- both nonzero z = 1 2 5 Note that the find function returns the indices, not the values. 4-34 (continued …)

35 Logical Operators and the find Function (continued) In the following session, note the difference between the result obtained by y(x&y) and the result obtained by find(x&y) in the previous slide. >>x = [3, 6, 0, 0, 1]; >>y = [4, -2, 1, 1, 3]; >>values = y(x&y) % y-values where x&y nonzero; from before x&y=[1 1 0 0 1] values = 4 -2 3 >>how_many = length(values) how_many = 3 Very good use of find() in Projectile function example – see notes and code !!! 4-35More? See pages 198-199.

36 The if Statement The if statement’s basic form is if logical expression statements end clear all x = 10; y = -50; if ( (x > 0) & (y < 0) ) z = log(x); w = sqrt(-y); end z W 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-36More? See pages 201-202. Note, no braces { } like in C

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 4-37More? See pages 202-205.

38 Flowchart of the else structure. Figure 4.4–2 4-38 if ( x > 0 ) %x is scalar, (x>0) is logical disp(‘x is positive’) else disp(‘x is not positive’) end

39 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

40 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 < 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 < 0 is false, when this program is run it gives the result y = 20 + 3.000i5 % get complex root 4-40

41 Instead, consider what happens if we test for x positive. x = [4,-9,25]; if x >= 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 = 0 also returns a false value because x >= 0 returns the vector [1,0,1]. 4-41

42 NOTE that the following statements if ( x > 0 ) if ( y > 0 ) % nested if statement statements end can be replaced with the more concise program if ( x>0 & y>0 ) statements end 4-42

43 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

44 Flowchart for the general if- elseif-else structure. Figure 4.4–3 4-44

45 4-45 Example: Assume marks is an array of students’ test scores marks = [ 56 84 94 67 68 86 54 58 ] avg = mean(marks) dev = std(marks) for j = 1:length(marks) if ( marks(j) > avg +dev ) grade(j) = 'A'; elseif ( marks(j) > avg -dev ) grade(j) = 'B'; else grade(j) = 'C'; end grade

46 Flowchart illustrating nested if statements. Figure 4.4–4 4-46 In Class: Ch4 #17 if x > 10 y = log(x) if ( y >=3 ) z = 4*y elseif ( y >= 2.5 ) z = 2*y else z = 0 end else y = 5*x z = 7*x end

47 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)); z = log(abs(x)); elseif ( nargin == 2) z = log(abs(x+y)); z = log(abs(x+y));else disp(‘error’) disp(‘error’)end Analogously, nargout gives you the number of output arguments

48 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: >>name = ’Leslie Simpson’ name = Leslie Simpson 4-47 (continued …)

49 Strings (continued) The following string, number, is not the same as the variable number created by typing number = 123. >>number = ’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(8:end) gives the last name Simpson Can manipulate columns as we do vectors; for example to insert a middle initial letter: fullname = [ name(1:6), ‘A.’, name(7:end)] fullname(8) = ‘D’ % change it to D Can use findstr to find locations of certain characters. findstr(fullname,’i’) get locations 5 and 124-48 Leslie Simpson Leslie D. Simpson

50 Strings (continued) Two strings are equal if and only if 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

51 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

52 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)|(response==’Y’)|(response==’y’)) response = ’Y’ else response = ’N’ end 4-50More? See pages 209-210.

53 for Loops A simple example of a for loop is for k = 5:10:35 x = k^2 end The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. 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

54 Flowchart of a for Loop. Figure 4.5–1 Typical structure of the loop: for loop variable = m:s:n 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 4-52

55 Note the following rules when using for loops with the loop variable expression k = m:s:n: The step value s may be negative. Example: k = 11:-3:5 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. Better to avoid it!!! 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

56 We may nest loops with conditional statements and with other loops. Example: Create a matrix with 1’s in 1 st row and column and with other elements which are sums of two elements above and to the left if the sum < 20, otherwise max. function A = specmatrix(n) A = ones(n); for r = 1:n for c = 1:n for c = 1:n if ( r > 1 & c > 1 ) if ( r > 1 & c > 1 ) s = A(r-1,c) + A(r,c-1); s = A(r-1,c) + A(r,c-1); if s < 20 if s < 20 A(r,c) = s; A(r,c) = s; else else A(r,c) = max(A(r-1,c),A(r,c-1)); A(r,c) = max(A(r-1,c),A(r,c-1)); end end end

57 The break and continue Statements break – terminates the loop, but does not stop the program for k = 1:7 x = 10-k^3 if x < 0 break end y(k) = log10(x); end Usually possible to write the code which avoids break – using while loop. The runs through the following values of x: x = 9 x = 2 x = -17 4-54 More? pp 210-217.

58 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 = NaN*x; for k = 1:length(x) if x(k) < 0 continue end y(k) = log10(x(k)); end y The result is y = 1, 3, NaN, 2.

59 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 = k^2 y = k^2end A = [ 1 3 -2 4 ] -2 4 ] for V = A % will go through matrix A column by column y = v.^2 y = v.^2end y = 1 4 y = 9 16 16 Ex: Compute the distance from 0 to a set of pts given by columns for a matrix k = 0 A = [ 1 3 7 -2 4 2] -2 4 2] for coord = A k = k + 1; k = k + 1; dist(k) = norm(coord); dist(k) = norm(coord);end [maxdist, farthest] = max(dist);

60 Implied Loops All Matlab commands acting on arrays imply loops: x = linspace(-1,4,100); y = sin(x).^2.* exp(-x); find (y>0); Each line above requires a loop in most other languages!!! Also in Matlab, array operations work much, much faster than loops

61 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. >>A = [ 0 -1 4 9 -14 25 -34 49 64]; >>C = (A >= 0); The result is C =C = 1 0 1 0 1 14-55

62 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 >= 0); A(C) = sqrt(A(C)) A(~C) = A(~C) + 50 Rocket example 4.5-2 – interesting, but a bit hard and long. 4-56More? See pages 217-218.

63 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 <= 31 disp(x) % loop body x = 3*x + 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. Note that while x becomes 94 at the end of the loop, the loop condition stops the loop and this value is never displayed.4-57

64 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: 1.The loop variable must have a value before the while statement is executed – initialization. 2.The loop variable must be changed somehow by the statements. Note that both of these steps are done automatically for the for – loop. Also: NEVER compare two real numbers for equality if ( x==y), while ( x == y ) instead use: while( abs (x - y)< 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

65 Flowchart of the while loop. Figure 4.5–3 4-59

66 4-60 Example. How long does it take to double the balance at a given rate of 5% annual interest?

67 4-61 Bisection Algorithm :

68 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

69 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 4-63 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 1 st statement after the end!!!

70 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-64More? See pages 225-227.

71 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

72 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 case min minimum = min(x) minimum = min(x) case max case max maximum = max(x) maximum = max(x) case sum case sum total = sum(x) total = sum(x) otherwise otherwise disp(‘entered wrong choice’) disp(‘entered wrong choice’)end

73 The Editor/Debugger containing two programs to be analyzed. Figure 4.7–1 Study those pages! Very important for debugging large programs 4-65More? See pages 228-234. Octave has Debug in Editor several options. Also in the code you can include debug_on_warning(1); debug_on_error(1); this is to enter debug mode in Octave whenever a warning or error occurs. To add a breakpoint, use dbstop('yourfunctionname',1) where 1 is the line number where you want to stop. To go to next line, type dbnext To step into type dbstep To continue running, type dbcont

74 The remaining slides show figures from Chapter 4 and its homework problems. 4-66

75 Duration above 50,000 ft as a function of the burn time. Figure 4.5–2 4-67

76 The state transition diagram for the college enrollment model. Figure 4.8–1 4-68

77 Class enrollments versus time. Figure 4.8–2 4-69

78 Figure P19 4-70

79 Figure P24 4-71

80 Figure P25 4-72

81 Figure P29 4-73

82 Figure P30 4-74

83 Figure P31 4-75

84 Figure P32 4-76


Download ppt "Chapter 4 Programming with MATLAB. Algorithms and Control Structures Algorithm: an ordered sequence of precisely defined instructions that performs some."

Similar presentations


Ads by Google