Lecture 3 MATLAB programming (1) Dr .Qi Ying
Objectives Data types Logical operators/functions Branching Debugging of a program
A Simple MATLAB program
Data types in MATLAB Basic: Advanced (will be discussed later): Numeric (integer, floating-point, complex) Logical: True, false Characters and string Advanced (will be discussed later): Structure Function handles Look-up table User-defined data types
Logical Data Type Assign a logical data to a variable: a1 = true; (equivalent to: a1 = 1) b2 = false; (equivalent to: b2 = 0) c3 = 5 > 4; % relational operators return logical data
Relational operators Operators with two operands (typically numerical or string) that yield a logical result A1 OP A2 List of OPs == equal to ~= not equal to > greater than < less than >= greater than or equal to <= less than or equal to
Relational operators Relational operators on arrays the result of the operation is an array of logical values If a1 and a2 are both arrays, they have to be of the same size It is also valid if one of the operands is a scalar Relational operators on strings The strings have to be of the same length Relational operators are evaluated after all arithmetic operators have been evaluated 7 + 3 < 2 + 11 is equivalent to (7+3)<(2+11) Be careful of round off error when comparing two numerical values e.g. sin(pi) = 1.2246e-16 (which is not zero!).
Logic operators Operators with one or two logical operands that yield a logical results & Logical AND && Logical AND with shortcut evaluation | Logical inclusive OR || Logical inclusive OR with shortcut evaluation xor Logical exclusive OR ~ Logical NOT
Short-circuit evaluation Example: evaluate whether a/b is greater than 10 x = a/b>10.0 Better code to avoid potential “dividing-by-zero” error: x = (b ~= 0) && (a/b>10.0)
Hierarchy of operation All arithmetic operators are evaluated first All relational operators are evaluated, from left to the right All ~ operators are evaluated All & and && operators are evaluated from left to right All |, || and xor operators are evaluated from left to right
Logical functions isnan(a) true if a is NaN (not a number) isnumeric(a) true if a is a numerical variable isinf(a) true if a is Inf
Flow control of a program One of the most important concepts of programming is the ability to control the flow of a program. The mechanisms that allow us to control the flow of execution are called control structures. Sequence Branching Iteration (looping)
Branches Statements that permit selective execution of specific parts of code. The ‘if’ construct The ‘switch’ construct The ‘try/catch’ construct
The ‘If’ construct if control_expr_1 statement 1 statement 2 … elseif control_expr_2 else end Example: Solution of a quadratic equation: r=b^2 – 4*a*c; if r>0 disp(‘two distinct real roots’); elseif r==0 disp(‘two identical real roots); else disp(‘two complex roots’); end
The ‘If’ construct Nested ‘if’ construct
The ‘switch’ construct switch (switch_expr) case case_expr_1, statement 1 statement 2 … case case_expr_2, otherwise, end Example: switch (value) case {1,3,5,7,9}, disp (‘The value is odd.’) case {2,4,6,8,10}, disp (‘The value is even.’) otherwise, disp(‘The value is out of range.’) end
Switch Example: [dayNum, dayString] = weekday(date, 'long', 'en_US'); switch dayString case 'Monday' disp('Start of the work week') case 'Tuesday' disp('Day 2') case 'Wednesday' disp('Day 3') case 'Thursday' disp('Day 4') case 'Friday' disp('Last day of the work week') otherwise disp('Weekend!') end
The ‘try/catch’ construct try statement 1 statement 2 … catch end Example: a=[ 1 -3 2 5]; try index = input(‘Enter subscript of element to display: ‘); disp( [ 'a(' int2str(index) ')=' num2str(a(index)) ] ); catch % if we get here, an error occurred disp( [ ‘Illegal subscript: ‘ int2str(index) ] ); end
Debugging a program It is equally important to debug as to code. It is very important for new learners to trace through the entire code for variable changes and logic flow to make sure they behave as expected. Use the debug tool in the editor window. Set break point at where you would the program to pause to check intermediate results of variables Execute the program step by step. Variables and their current values are available at the workspace.
Program documentation % Wixon Valley City Boundary Project % Lab #2 % file name Wang_Code.m % % Purpose: % This program reads in the locations of the boundary corners of the Waxon % Valley City, Texas, converts them to state plane coordinates, and then % checks whether random points are inside or outside of an area of interest % within the city boundary. % Record of revisions: % Date Programmer Description of Changes % ========== ============ ======================== % 2/3/2010 B. Wang Original Code % Define variables: % points --- coordinates of boundary corners % WV-Boundary --- spherical coordinates of the boundary corners % p2 --- duplicate of the boundary corners with the first % and last being the identical to make convenient % drawing c closed shape % i --- index variable % n --- intermediate variable % latp --- latitude coordinates of points % longp --- longitude coordinates of points