MatLab Palm Chapter 4, Part 4 Review and Debugging Class 12.1: Palm Chapters 2.6-7 & 4.1-7 ENGR 111A - Spring 2004 1 EXAM #2: NOV. 17, 2004 Details: Wednesday, Nov. 17, 2004 6:30-8:00 p.m. Same room as last time

Bring: Drawing Tools, Calculator, Pencil Coverage: Material from Lecture 6.1 through 11.2. ENGR 111A - Spring 2004 2 EXAM #2, CONTINUED Alternate Exam Times: If you have a verifiable conflict, you can arrange with the instructor to take the exam at:

5:00 pm CVLB 420 with Kohutek By appointment Arrangements MUST be made by Nov. 16, 2004 ENGR 111A - Spring 2004 3 LEARNING OBJECTIVES Students should be able to: Run the Matlab Editor/Debugger

Window Set Preferences Follow Matlab Error Messages Debug User-Defined Programs ENGR 111A - Spring 2004 4 4.7 DEBUGGING(P. 201) Activate the Editor/Debugger window and browse the menu items Set Preferences is in the File menu

Text formatting tools (indents) are in the Text menu Find and replace tools are in the Edit menu ENGR 111A - Spring 2004 5 DEBUGGING MENU Load one of your old script files into the debug window and make sure that it has

the focus (is active). Click on the run item in the Debug menu. Notice the variables that were created in the workspace. You can find the values in the Command Window ENGR 111A - Spring 2004 6 SOME HINTS Until you get some experience, do NOT expect your code to run correctly the first time; so, plan to do some debugging.

Start at the top and look at the variable values and make sure you are getting what you expected. Point at the variable and a hint window with the values will appear. ENGR 111A - Spring 2004 7 MORE HINTS If your code generates an error message, try a fix and re-run. This may take some research on your part. Starting at the bottom of your program,

turn your statements into comments until you get something that actually runs. It is much harder to find algorithm errors (program runs but gives the wrong answer) than programming errors (program does not run or generates warnings). ENGR 111A - Spring 2004 8 EXAMPLE ERROR MESSAGE An M-file contains: x = 7; y = 8; if x = y x = y$2 else x = y(3

end Running at the command prompt gives: >> temp ??? Error: File: C:\Programs\MATLAB6p5\work\temp.m Line: 3 Column: 6 Assignment statements do not produce results. (Use = = to test for equality.) ENGR 111A - Spring 2004 9 EXAMPLE

Matlab only reported the first error it found. It gives you a link to the position in the files where the error occurred. It tells you what type of error (assignment statements do not produce results). And it suggests a fix (use == to test for equality). However, it still takes a LOT of practice to understand these error messages! ENGR 111A - Spring 2004 10 EXAM #2 REVIEW Chapters 2.6-7 and 4.2-6 in the Palm Matlab Book

ENGR 111A - Spring 2004 11 REVIEW TOPICS 2.6 Cell Arrays 2.7 Structure Arrays 3.2 Function Files 4.2 Relational Operators / Logical Variables

4.3 Logical Operators and Functions 4.4 ifend Conditional Structures 4.6 switchend Selection Structures 4.5 Loops (forend and whileend) ENGR 111A - Spring 2004 12 2.6 CELL ARRAYS Create a 2x2 Cell array named climate that stores the following table: Easterwood Nov. 6, 2004

[10 14 16 20] [2 5 4 7] Write a command to access the 5 in the matrix in the lower right-hand corner. ENGR 111A - Spring 2004 13 SOLUTION % Create Cell Array climate{1,1} = Easterwood; climate(1,2) = {Nov. 6, 2004}; climate{2,1} = [10 14 16 20]; climate(2,2) = {[2 4; 5 7]};

% Access element 2,1 of lower % right-hand matrix disp(climate{2,2}(2,1)) ENGR 111A - Spring 2004 14 2.7 STRUCTURE ARRAYS Create a Structure Array called student with fields name and grade (grade will be an array with three exam grades in it) Fill in your structure with made up data for three students

Write code to average the 2nd grade of all three students and display the result in the command window ENGR 111A - Spring 2004 15 SOLUTION % Create structure student(1).name = Fritz Hertz; student.grade = [87 92 78]; student(2).name = Uli Bonn; student(2).grade = [81 85 92]; student(3).name = Max Plank; student(3).grade = [94 95 92]; % Average grades ave_grade = sum([student.grade])/ length(student); % Display 2nd grade disp(ave_grade(2))

ENGR 111A - Spring 2004 16 3.2 FUNCTION FILES User-defined function: take inputs and compute outputs; variables are local (that means they are deleted when the function finishes. General form: function [outputs] = my_name(inputs) At Matlab prompt type: >>[ouputs] = my_name(inputs)

ENGR 111A - Spring 2004 17 EXAMPLE Write a function to compute the volume and surface area of a sphere given the diameter as input. Volume: V = 4r3/3 Surface Area A = 4r2 ENGR 111A - Spring 2004

18 SOLUTION function [V, A] = sphere(r) % r = radius of a sphere % V = Volume of the sphere % A = Area of the sphere V = 4*pi*r.^3/3; A = 4*pi*r.^2; ENGR 111A - Spring 2004 19 SOLUTION CONTINUED >> sphere(4) ans = 268.0826 >> V = sphere(4)

V = 268.0826 >> [V, A] = sphere(4) V = 268.0826 A = 201.0619 ENGR 111A - Spring 2004 20 4.2 RELATIONAL OPERATORS Matlab has 6 relational operators to make comparisons

< > <= >= == ~= less than greater than less than or equal to greater than or equal to equal to not equal to

Result of comparison: 1 is True and 0 is False ENGR 111A - Spring 2004 21 4.3 LOGICAL OPERATORS Matlab has three logical operators ~ not is used to change true to false and false to true & and links logical expressions e.g. (x < y) & (y > z)

| or links logical expressions e.g. (x < y) | (y > z) ENGR 111A - Spring 2004 22 ORDER OF PRECEDENCE Comparison statements are evaluated according to the following strict order of precedence: 1. 2. 3. 4. 5.

Parenthesis starting with innermost Arithmetic operators and ~ evaluated from left to right Relational operators evaluated from left to right & operator (logical AND) | operator (logical OR) ENGR 111A - Spring 2004 23 EXAMPLES

x = [6, 3, 9] y = [14, 0, 9] z = ~x returns z = ? z = ~x > y or z = (~x) > y returns z =? z = ~(x > y) returns z = ? What would z = x>~y return? What would z = x~>y return? ENGR 111A - Spring 2004 24 SOLUTION >> x = [6, 3, 9] >> y = [14, 0, 9] >> z = ~x z = 0 0 0

>> z = ~x > y z = 0 0 0 >> z = ~(x > y) z = 1 0 1 >> z = x > ~y z = Notice, Matlab is pointing 1 1 1 to where it found an error >> x ~> y ??? x ~> y |

Error: Missing operator, comma, or semicolon. ENGR 111A - Spring 2004 25 4.4 SELECTION STRUCTURES ifelseifelseend. Most general form: if logical expression 1 statement group 1 elseif logical expression 2 statement group 2 else statement group 3 end

Only one statement group will execute no matter what! ENGR 111A - Spring 2004 26 4.5 ITERATION STRUCTURES forend and whileend loops for variable = start:step:stop statements end while logical expression statements (must change logical expression) end ENGR 111A - Spring 2004

27 BREAK AND CONTINUE break exits a loop. Used to halt a certain process, like a file read of unknown length. continue jumps to the end of a loop, but keeps on iterating. Used to skip bad values (like divide by zero). ENGR 111A - Spring 2004 28

EXAMPLE Write a program to find the index of the maximum value in a matrix. First, write your program with a for end loop Second, write your program with a whileend loop ENGR 111A - Spring 2004 29 SOLUTION: FOR-LOOP [m,n] = size(A);

max_val = A(1,1); for r = 1:m for c = 1:n if A(r,c) > max_val max_row = r; max_col = c; max_val = A(r,c); end end end ENGR 111A - Spring 2004 30 SOLUTION: WHILE-LOOP r = 1; [m, n] = size(A); max_val = A(1,1); while r <= m c = 1;
while c <= n if A(r,c) > max_val max_row = r; max_col = c; max_val = A(r,c); end c = c+1; end r = r+1; end ENGR 111A - Spring 2004 31 4.6 SWITCH CASE switchend. Most general form: switch variable

case value1 statement group 1 case value2 statement group 2 otherwise default case end ENGR 111A - Spring 2004 Name of a variable containing the value of the switch parameter Possible values that the switch parameter might have 32 EXAMPLE

Given the following grades and numbers of credit hours: grades = [A, B, B, C] hours = [2, 3, 3, 4] Use a switch structure inside of a for loop to compute a students GPR Note that A=4.0, B=3.0, etc. ENGR 111A - Spring 2004 33 SOLUTION n = length(grades);

total = 0; for k = 1:n switch grades(k) case 'A' value = 4.0; case 'B' value = 3.0; case 'C' value = 2.0; end total = total + value*hours(k); end gpr = total / sum(hours); ENGR 111A - Spring 2004 34 ASSESSMENT

Take out a sheet of paper and individually write a brief description of the MatLab topic that is the muddiest to you to date. Then, as a team, agree on a topic you would like for the TA to cover in help sessions. Write this on a sheet of paper along with your Team # and give this paper to the TA as you leave. Please note on you paper if you are usually missing a team member for class assignments or homework. ENGR 111A - Spring 2004 35 ASSIGNMENT 12.1

Individual assignment Due: Tuesday, November 23, 2004 In-Class work that you did not finish by the end of this class. Study for the exam. Read Ch. 5.1-5.4 in the Palm Matlab book ENGR 111A - Spring 2004 36