Lecture 3 MATLAB programming (1)

Slides:



Advertisements
Similar presentations
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Advertisements

3. S/E with Control Structures 3.1 Relational Operators and Expressions 3.2 If and if-else Statements 3.3 The Type Double 3.4 Program Design with the While.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Chapter 8 Branching Statements and Program Design.
Programming with MATLAB. Relational Operators The arithmetic operators has precedence over relational operators.
MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
CSE123 Lecture 3 Different types of Variables Logical operators, Conditional Statements and If Blocks.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
October 3, 2005 Lecture 8 - By Paul Lin 1 CPET 190 Lecture 8 Problem Solving with MATLAB
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
CSE123 Lecture 3 Files and File ManagementScripts.
MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Conditional Logic in MATLAB By Bruce Raine. How to do a basic IF – END structure in MATLAB if MATLAB Commands end i.e. do the MATLAB commands if the conditional.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 4 Monday 06 Oct 2014 EGR 115 Introduction to Computing for Engineers.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Chapter 4: Decisions and Conditions
The Ohio State University
Program design Program Design Process has 2 phases:
Matlab Programming for Engineers
CNG 140 C Programming (Lecture set 3)
Chapter 4: Decisions and Conditions
CprE 185: Intro to Problem Solving (using C)
Lecture 3: Operators, Expressions and Type Conversion
Control Statements in Matlab
Visual Basic 6 (VB6) Data Types, And Operators
Chapter 4: Making Decisions.
Chapter 5 - Control Structures: Part 2
CHAPTER 4 Selection CSEG1003 Introduction to Computing
EGR 2261 Unit 4 Control Structures I: Selection
CS1371 Introduction to Computing for Engineers
Selection Statements by Ahmet Sacan
Chapter 4: Making Decisions.
Scripts & Functions Scripts and functions are contained in .m-files
Introduction to MATLAB
Web Systems Development (CSC-215)
Conditional Statements
Introduction to Programming
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Logical Operations In Matlab.
Relational & Logical Operators, if and switch Statements
INTRODUCTION TO MATLAB
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Introduction to Programming
Matlab Basics.
COMS 261 Computer Science I
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

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