MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳

Slides:



Advertisements
Similar presentations
Chapter 3 IF & SELECT. Control Constructs: Branches Definitions: Code: statements or expressions in a program Block: a group of codes Branching: selecting.
Advertisements

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.
Chapter 3 Program Design And Branching Structures.
The LC-3 – Chapter 6 COMP 2620 Dr. James Money COMP
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
 Control structures  Algorithm & flowchart  If statements  While statements.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
17 March, 2000 CS1001 Lecture 2 Programming and problem solving Software engineering practices.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Chapter 3 Program Design and Branching Structures Dr. Ali Can Takinacı İstanbul Technical University Faculty of Naval Architecture and Ocean Engineering.
Chapter 2: Algorithm Discovery and Design
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 > =
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering
Class 9.1 Chapter 4 Sections: 4.1, 4.2, 4.3
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Top-down Program Design, Relational and Logical Operators
Top-down Program Design Selim Aksoy Bilkent University Department of Computer Engineering
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Program Design, Relational and Logical Operators Selim Aksoy Bilkent University Department of Computer Engineering
Algorithms. Introduction Before writing a program: –Have a thorough understanding of the problem –Carefully plan an approach for solving it While writing.
C++ for Engineers and Scientists Third Edition
Chapter 8 Branching Statements and Program Design.
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 2: Algorithm Discovery and Design
Relational and Logical Operators Selim Aksoy Bilkent University Department of Computer Engineering
Fundamentals of Python: From First Programs Through Data Structures
MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014
Fundamentals of Python: First Programs
Invitation to Computer Science, Java Version, Second Edition.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Chapter 4 Selection Structures: Making Decisions.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Flow of Control Part 1: Selection
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.
Fall, 2006Selection1 Choices, Choices, Choices! Selection in FORTRAN Nathan Friedman Fall, 2006.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
VBScript Language. What is VBScript Based on the Visual Basic family of languages Supports object oriented features Interpreted Loosely Typed Implicitly.
Introduction to Programming with RAPTOR
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Branches and Program Design
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
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”
Chapter 3. Control Structures and Program Design ► Two broad categories of control statement:  Branches  Loops ► These will make the program more complex.
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.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Introduction to Computer Sciences References: [1] Fortran 95/2003 for Scientists and Engineers (3e) by Stephen J. Chapman. [2] Using Fortran 90 by Chester.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 4 Monday 06 Oct 2014 EGR 115 Introduction to Computing for Engineers.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Matlab Programming for Engineers
L2. Basics Variables and Expressions Assignment Statements
The Selection Structure
Lecture 3 MATLAB programming (1)
Conditional Statements
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Matlab Basics.
Presentation transcript:

MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳

补充 : X1:inc:x2 linspace(x1,x2,N) generates N points between x1 and x2 x = linspace(10,20,5) x = logspace(x1,x2) can be used for logarithmically equally spaced points

Top-down Program Design & Relational and Logical Operators CHAPTER 3 Branching Statements And Program Design

Abstract Sequential programs: Branches: if, switch, try/catch Loops: Top-down Program Design Relational and Logical Operators

3.1 Top-down design concept Top-down design is the process of starting with a large task and breaking it down into smaller, more easily understandable pieces (subtasks), which perform a portion of the desired task. Each subtask may in turn be subdivided into smaller subtasks if necessary. Once the program is divided into small pieces, each piece can be coded and tested independently. We do not attempt to combine the subtasks into a complete task until each of the subtasks has been verified to work properly by itself.

Top-down Program Design process program Start State the problem Define inputs and outputs Design the algorithm Convert algorithm into MATLAB statements Test the resulting program End Decomposition Stepwise refinement

steps 1.Clearly state the problem that you are trying to solve 2.Define the inputs required by the program and the outputs to be produced by the program 3.Design the algorithm that you intend to implement in the program 4.Turn the algorithm into MATLAB statement 5.Test the resulting MATLAB program 1/3 time 1/6 time 1/2 time

Testing Test individual subtasks: unit testing Add tested components one by one and test them together: build Alpha release: Beta release Test for all legal input data sets: standard data sets, ground truth

A typical testing process for a large program Start Unit testing of individual subtasks Successive builds (adding subtasks to the program) Alpha release Beta release Minor bugs fixed Finished program As many times as necessary Subtasks validated separately Subtasks combined into a single program Worst bugs fixed

3.2 Use of Pseudocode A hybrid mixture of MATLAB and English for defining algorithms Independent of any programming language so it can be easily converted to any programming language

example 1 Problem: write a program that takes the radius and height (in meters) of a cylinder tank and the amount of water (in m 3 ) from the user and output the amount of extra space (in m 3 ) in the tank. Input: radius and height amount of water Output: extra space

example 1 Design: 1. Get radius of the tank base from the user 2. Get the height of the tank from the user 3. Get the amount of water 4. Calculate the amount of extra space 5. Write the result Step 4 is not clear enough, refine it: Calculate the capacity of the tank (pi * radius^2 * h) extra space  capacity - water

example 1 Code: r = input('Enter the radius of the tank base:'); h = input('Enter the height of the tank:'); water = input('Enter the amount of water:'); capacity = pi * r^2 * h; space = capacity - water; fprintf('There is %f m3 extra space in the tank', space);

example 1 Testing: Enter the radius of the tank base:2 Enter the height of the tank:5 Enter the amount of water:10 There is m3 extra space in the tank Continue testing: Enter the radius of the tank base:2 Enter the height of the tank:5 Enter the amount of water:100 There is m3 extra space in the tank

3.3 Relational and Logical Operators Relational Operators Relational operators are used to represent conditions (such as “ space  0 ” in the water tank example)example Result of the condition is either true or false In MATLAB: false is represented by 0 true is represented by 1 (non-zero)

The general form: a1 op a2 a1 and a2 are: arithmetic expressions,variables, or strings Op: in table 3.1(==,~=,>,>=,<,<=) If the relationship between a1 and a2 expressed by the operator is true, then the operation returns a value of 1; Otherwise, the operation returns a value of 0

OperationResult 3 < 41 3 <= 41 3 == 40 3 ~= 41 3 > 40 4 >= 41 ‘ A ’ < ‘ B ’ 1

Scalar and array: a=[1 0;-2,1], b=0,a>b Two array a=[1 0;-2,1], b=[0 2;-2 -1],a>=b Evaluated after all arithmetic 7+3<2+11 (7+3)<(2+11)

3.3.2 Relational Operators ==and ~= Don’t confuse equivalence (==) with assignment (=) Relational operations have lower priority than arithmetic operations (use parentheses to be safe)

Be careful about round off errors during numeric comparisons. Example: a=0; b=sin(pi) a==b abs(a-b)<1.0e-14 (you can represent “x == y” as “abs(x-y) < 1.0e-14”)

3.3.3 Logical Operators More complex conditions can be represented by combining relational operations using logic operators l1 op l2 Logical operators: &AND |OR xorExclusive OR ~NOT

Logical Operators inputandorxornot aba & ba | bxor(a,b)~a

Scalar and array: a=[1 0; 0,1], b=0,a&b Two array a=[1 0; 0,1], b=[1 1; 0 0],a|b

Operator Hierarchy Processing order of operations: 1.parenthesis (starting from the innermost) 2.exponentials (left to right) 3.multiplications and divisions (left to right) 4.additions and subtractions (left to right) 5.relational operators (left to right) 6.~ operators 7.& operators (left to right) 8.| operators (left to right)

example 2 Assume that the following variables are initialized with the values shown, and calculate the result of the specified expressions, value1=1, value2=0, value3=-10

3.3.4 Logical Functions Table 3.4 ischar(a) isempty(a) isinf(a) isnan(a) isnumeric(a) …… Quiz 3.1

3.4 Branches Branches are used to select and execute specific sections of the code while skipping other sections Selection of different sections depend on a condition statement We will learn: if statement switch statement

Branches: “ if ” Statement if ( condition ), statement 1 statement 2... end condition statement group true false statement group if end

Example 1 Examples: if ( r <= 0 ), disp( [ ‘ Radius must be positive ’ ] ); end if ( ( grade 100 ) ), disp( [ ‘ Grade must be in [0,100] range ’ ] ); end if isinf( result ), disp( ‘ Result is infinite ’ ); end

Example 2 Water tank example: r = input('Enter the radius of the tank base (in meters):'); if ( r 0 ), disp( [ 'There is ' num2str(space) ' m3 extra space' ] ); else disp( 'Tank is full' ); end

Branches: “ if-else ” Statement if ( condition ), statement 1 statement 2... else statement 1 statement 2... end condition statement group 1 truefalse statement group 2 statement group 1 statement group 2 if end

Branches: “ if-elseif-else ” Statement if ( condition 1 ), statement 1 statement 2... elseif ( condition 2 ), statement 1 statement 2... else statement 1 statement 2... end statement group 1 condition 1 statement group 1 truefalse condition 2 statement group 2 statement group 3 truefalse statement group 2 statement group 3 if end

Branching Example 3.2 Example: Finding roots of the quadratic equation “ ax 2 + bx + c = 0 ” Pseudocode: d = b 2 – 4ac if d > 0, two real roots elseif d == 0, two identical roots else two complex roots

Branching Examples % Prompt the user for the coefficients of the equation disp ('This program solves for the roots of a quadratic '); disp ('equation of the form A*X^2 + B*X + C = 0. '); a = input ('Enter the coefficient A: '); b = input ('Enter the coefficient B: '); c = input ('Enter the coefficient C: '); % Calculate discriminant discriminant = b^2 - 4 * a * c; % Solve for the roots, depending on the value of the discriminant

if discriminant > 0 % there are two real roots, so... x1 = ( -b + sqrt(discriminant) ) / ( 2 * a ); x2 = ( -b - sqrt(discriminant) ) / ( 2 * a ); disp ('This equation has two real roots:'); fprintf ('x1 = %f\n', x1); fprintf ('x2 = %f\n', x2); elseif discriminant == 0 % there is one repeated root, so... x1 = ( -b ) / ( 2 * a ); disp ('This equation has two identical real roots:'); fprintf ('x1 = x2 = %f\n', x1); else % there are complex roots, so... real_part = ( -b ) / ( 2 * a ); imag_part = sqrt ( abs ( discriminant ) ) / ( 2 * a ); disp ('This equation has complex roots:'); fprintf('x1 = %f +i %f\n', real_part, imag_part ); fprintf('x2 = %f -i %f\n', real_part, imag_part ); end

Branching Examples Example: Assigning letter grades How can we compute the letter corresponding to a given numeric grade? RangeGrade 100  grade > 95 A 95  grade > 86 B 86  grade > 76 C 76  grade > 66 D 66  grade > 0 F

Branching Examples Letter grade example: grade= input ('Enter the value of grade:'); if ( grade > 95 ), disp( ‘ Grade is A ’ ); elseif ( grade > 86 ), disp( ‘ Grade is B ’ ); elseif ( grade > 76 ), disp( ‘ Grade is C ’ ); elseif ( grade > 66 ), disp( ‘ Grade is D ’ ); else disp( ‘ Grade is F ’ ); end

Branching Examples if ( grade > 95 ), disp( ‘ Grade is A ’ ); else if ( grade > 86 ), disp( ‘ Grade is B ’ ); else if ( grade > 76 ), disp( ‘ Grade is C ’ ); else if ( grade > 66 ), disp( ‘ Grade is D ’ ); else disp( ‘ Grade is F ’ ); end nested if statements

Example Evaluating a Function of Tow Variable and

3.4.4 “ switch ” Statement switch ( expression ), case value 1, statement 1 statement 2... case value 2, statement 1 statement 2... end statement group 1 statement group 2  expression is a scalar or string constant

Branches: “ switch ” Statement switch ( expression ), case {value set 1}, statement 1 statement 2... case {value set 2}, statement 1 statement 2... otherwise, statement 1 statement 2... end statement group 1 statement group 2 optional statement group that is executed if none of the cases is satisfied

Branching Examples Example: Odd or even numbers value=input('please enter the value:') switch (value), case {1,3,5,7,9}, disp( 'Odd number' ); case {2,4,6,8,10}, disp('Even number'); otherwise, disp('Out of range'); end

Branches: “ try/catch ” Statement try statement 1 statement 2... catch statement 1 statement 2... end Try Block Catch Block

a=[1 2 3;4 5 6]; b=[7 8 9; ]; try c=a*b catch d=a.*b end

Branching Examples Example: % Initialize array a=[ ]; try %Try to display an element index=input('Enter subscript of element todisplay: '); disp( [ 'a(' int2str(index) ')=' num2str(a(index)) ] ); catch %If we get here an error occurred disp(['Illegal subscript: ' int2str(index)]); end Quiz 3.2

3.7 Summary Top-down Program Design Basic types of MATLAB branches (if, switch, try/catch) Relational and Logical Operators Additional information about plots(axis,hold subplot) Control additional characteristics pf plots(boldface,italic,superscripts,font size,font name)

3.7.1 Summary of good programming practice 1.round off 2.Follow the steps of the program design process 3.If and switch constructs

3.7.1 MATLAB summary axis figure hold if ischar isempty iIsnan isnumeric polar subplot switch try/catch construct

Exercises