Programming in MATLAB Part 2

Similar documents
Computer Programming ECIV 2303 Chapter 6 Programming in MATLAB Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

Chapter 7: Programming in MATLAB

Lecture 3 Programming in MATLAB. Dr. Bedir Yousif

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Programming for Experimental Research. Flow Control

Repetition Structures Chapter 9

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

Control Structures. March 1, Dr. Mihail. (Dr. Mihail) Control March 1, / 28

Thinking Like an Engineer. Instructor Slides

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Short Version of Matlab Manual

ECE 102 Engineering Computation

Branches, Conditional Statements

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

ENGR 1181 MATLAB 09: For Loops 2

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

3 The L oop Control Structure

Flow Control. Statements We Will Use in Flow Control. Statements We Will Use in Flow Control Relational Operators

Introduction to Matlab. By: Hossein Hamooni Fall 2014

MATLAB for Chemical engineer

function [s p] = sumprod (f, g)

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Programming 1. Script files. help cd Example:

Unit 2: Accentuate the Negative Name:

CEMTool Tutorial. Control statements

CITS2401 Computer Analysis & Visualisation

Scientific Computing with MATLAB

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Boolean Logic & Branching Lab Conditional Tests

ECE 202 LAB 3 ADVANCED MATLAB

Mathcad Lecture #3 In-class Worksheet Functions

Chapter 1 Introduction to MATLAB

REPETITIVE EXECUTION: LOOPS

Lecture 15 MATLAB II: Conditional Statements and Arrays

MATLAB Operators, control flow and scripting. Edited by Péter Vass

2.0 MATLAB Fundamentals

7 Control Structures, Logical Statements

Introduction to programming in MATLAB

PROGRAMMING IN C AND C++:

The Mathematics of Big Data

Mth 60 Module 2 Section Signed Numbers All numbers,, and

Tribhuvan University Institute of Science and Technology 2065

Python for Informatics

AN INTRODUCTION TO MATLAB

Computer Programming : C++

An Introduction to MATLAB

MATLAB. Devon Cormack and James Staley

Introduction to MATLAB

CS 221 Lecture. Tuesday, 11 October 2011

Introduction to MATLAB

Digital Image Analysis and Processing CPE

Big Mathematical Ideas and Understandings

Matlab and Octave: Quick Introduction and Examples 1 Basics

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Dr. Iyad Jafar. Adapted from the publisher slides

EP375 Computational Physics

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Matlab (Matrix laboratory) is an interactive software system for numerical computations and graphics.

1. Represent each of these relations on {1, 2, 3} with a matrix (with the elements of this set listed in increasing order).

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

ENGR 1181c Midterm Exam 2: Study Guide and Practice Problems

Taking Apart Numbers and Shapes

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Precalculus Notes: Unit 7 Systems of Equations and Matrices

Computer Vision. Matlab

MATH LEVEL 2 LESSON PLAN 1 NUMBER TO INTEGER Copyright Vinay Agarwala, Checked: 06/02/18

Introduction to Matlab

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Introduction to Matlab

ALGORITHMS AND FLOWCHARTS

MatLab Just a beginning

Relational and Logical Operators. MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs. Examples. Logical Operators.

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs

This is the basis for the programming concept called a loop statement

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Computer Programming in MATLAB

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Physics 326G Winter Class 6

UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA C ASSIGNMENTS

Chapter 4 Branching Statements & Program Design

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Programming for Engineers Iteration

Chapter 1 Section 1 Solving Linear Equations in One Variable

Summary of the Lecture

McTutorial: A MATLAB Tutorial

Introduction. C provides two styles of flow control:

C/C++ Programming for Engineers: Matlab Branches and Loops

Introduction to MATLAB LAB 1

2 T. x + 2 T. , T( x, y = 0) = T 1

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Matlab- Command Window Operations, Scalars and Arrays

Section Learning Objective Media You Examples Try

Chapter 1: Number and Operations

Conditionals and Recursion. Python Part 4


Transcription:

Programming in MATLAB Part 2 A computer program is a sequence of computer commands. In a simple program the commands are executed one after the other in the order they are typed. MATLAB provides several tools than can be used to control the flow of a program. Conditional statements make it possible to skip commands or to execute specific groups of commands in different situations. For loops and while loops make is possible to repeat a sequence of commands several times. CONTROL FLOW To build useful programs it is vital to have evaluation and re-direction facilities during execution. In evaluating conditions we use RELATIONAL and LOGICAL operators: RELATIONAL OPERATORS Operator Interpretation < less than > greater than < = less than or equal to > = greater than or equal to = = equal ~ = not equal The relational operators can be used to form logical expressions which are evaluated as true[1] or false[0]. MATLAB returns 1 for true, and 0 for false. e.g. If a = [2 ] and b = [3 ] then the logical expression a <b is true[1] COMPOUND EXPRESSIONS Logical expressions can be combined into compound expressions using connectors : Connector Interpretation & AND Operates on two operands (A and B). If both are true, the results is true(1); otherwise the result is false OR Operates on two operands (A and B). If either one or both are true the results in true (1); otherwise (both are false) the result is false (0)

~ NOT Operates on one operand (A). Gives the opposite of the operand; true(1) if the operand is false and false (0) if the operand is true. First & Second Compound 1 1 1 1 0 0 0 1 0 0 0 0 Example: a<b & a<c First Second Compound 1 1 1 1 0 1 0 1 1 0 0 0 Example: a<b a<c NOT is the logical complement, returning 0 for non-zero elements, and 1 for zero elements. i.e If a<b is true then ~(a<b) is false.

The results of a relational operation with vectors, which are vectors with 0s and 1s are called logical vectors and can be used for addressing vectors. When a logical vector is used for addressing another vector, it extracts from that vector the elements in the position where the logical vector has 1s. Eg.

This inequality is correct mathematically. The answer however is false since MATLAB executes from left to right. -5<x is true (=1) and then 1<-1 is false (0) The mathematically correct statement is obtained by using the logical operator &. The inequalities are executed first. Since both are true(1), the answer is 1. y<7 is executed first, it is true(1), and ~1 is 0 ~y is executed first. y is true (1)(since y is nonzero), ~1 is 0, and 0<7 is true(1) y>=8 (false), and x<-1 (true) are executed first. OR is executed next(true).~is executed last, and gives false(0). y>=8 (false), and x<-1 (true) are executed first. NOT of (y>=8) is executed next (true). OR is executed last, and gives true (1). Sample Problem: Analysis of temperature data. The following were the daily maximum temperatures in deg. C in Washington D.C., during the month of April.: 14 23 23 12 10 9 13 23 23 19 21 17 23 28 28 33 34 32 33 27 15 21 13 18 17 19 18 23 17 21. Use relational and logical operations to determine the following. (a) The number of days the temperature was above 24 deg. C (b) The number of days the temperature was between 18 and 27 (c) The days of the month when the temperature was between 10 and 16

Conditional Statements A conditional statement is a command that allows MATLAB to make a decision on whether to execute a group of commands that follow the conditional statement or to skip these commands. In a conditional statement a conditional expression is stated. If the expression is true, a group of commands that follow the statement are executed. If the expression is false the computer skips the group. Eg. if a<b if c>=5 if a==b if a~=0 if (d<h)&(x>7) if (x~=13) (y<0)

Conditional statements can be part of a program written in a script file or a user defined function. For every if statement there is an end statement The if statement is commonly used in three structures, if-end, if-else-end, and if-elseif-else-end. The if-end Structure The if-end conditional statement is shown schematically below. The figure shows how the commands are typed in the program and a flowchart that symbolically shows the flow or sequence in which the commands are executed. As the program executes, it reaches the if statement. If the conditional expression in the if statement is true(1), the program continues to execute the commands that follow the if statement all the way down to the end statement. If the conditional expression is false (0), the program skips the group of commands between the if and the end and continues with the commands that follow the end. The words if and end appear on the screen in blue and the commands between the if and end statement are automatically indented which makes the program easier to read. Eg. A worker is paid according to his hourly wage up to 40hours and 50% more for overtime. Write a program in a script file that calculates the pay to the worker. The program asks the user to enter the number of hours and the hourly wage. The program then displays the pay.

The if-else-end statement The if-else-end structure provides a means for choosing one group of commands out of a possible two groups for execution. The if-else-end structure is shown below. The figure shows how the commands are typed in the program and a flowchart illustrates the flow or sequence in which the commands are executed. The first line is an if statement with a conditional expression. If the conditional expression is true the program executes group 1 of commands between the if and the else statements and then skips to the end. If the conditional expression is false the program skips to the else and then executes group 2 of commands between the else and the end. Example: The systolic and diastolic blood pressure readings are found when the heart is pumping and the heart is at rest, respectively. A biomedical experiment is being conducted only on subjects whose blood pressure is optimal. This is defined as a systolic blood pressure less than 120 and a diastolic less than 80. Write a script file than will prompt for both blood pressure values and will print whether the person is a candidate for the experiment or not.

The if-elseif-else-end statement The if-elseif-else-end structure is shown below. The figure shows how the commands are typed in the program and gives a flowchart that illustrates the flow or the sequence in which the commands are executed. This structure includes two conditional statements (if and elseif) that make it possible to select one out of three groups of commands for execution. The first line is an if statement with a conditional expression. If the conditional expression is true the program executes group 1 commands between the if and the elseif statements and then skips to the end. If the conditional expression in the if statement is false the program skips to the elseif statement. If the conditional expression in the elseif statement is true the program executes group 2 of commands between the elseif and the else and then skips to the end.

If the conditional expression in the elseif statement is false the program skips to the else and executes group 3 commands between the else and the end. Note: Several elseif statements and associated groups can be added to create a file with >3 options. Sample Problem In fluid dynamics, the Reynolds number Re is a dimensionless number used to determine the nature of a fluid flow. For an internal flow (eg. water flow through a pipe) the flow can be categorized as follows Re 2300 Laminar Region 2300<Re 4000 Transition Region Re> 4000 Turbulent Region. Write a script file that will prompt the user for the Reynolds number of a flow and will print the region the flow is in.

Example1: Develop a program to categrise an item from 1-4 depending on its weight. If the weight of the item is below 50 kg, it is classified as category 1, between 50-125 is category 2, between 125-200 is category 3, and above 200 is category 4. Example 2: Assume that UL-Bank now offers 9% interest on balances of less than 5000, 12% for balances of 5000 or more but less than 10,000 and 15% for balances of 10,000 or more. Develop a program to calculate a customer s new balance after one year.

Sample Problem The continuity equation in fluid dynamics for steady fluid flow through a stream tube equates the product of the density, velocity, and area at two points that have varying cross sectional areas. For incompressible flow, the densities are constant so the equation is A 1 V 1 = A 2 V 2. If the areas and V 1 are known, V 2 can be found as (A 1 /A 2 )*V 1 Therefore, whether the velocity at the second point increases or decreases depends on the areas at the two points. Write a script file that will prompt the user for the two areas in square feet, and will print whether the velocity at the second point will increase, decrease, or remain the same as at the first point.

LOOPS A loop is another method to alter the flow of a computer program. In a loop the execution of a command or a group of commands is repeated several times consecutively. Repeat LOOPS There are two types of repeat loops that can be used. The for loop and the while loop. We have already covered the while loop. In a loop the execution of a command or a group of commands is repeated several times consecutively. Each round of execution is called a pass. The for loops is used for a fixed number of passes and the while loop is used for an unknown number of repeat. Both types of loops can be terminated using the break command. In for-end loops the execution of a command or a group of commands is repeated a predetermined number of times. The form of loop is shown below. Loop index variable Value of k in the first pass The increment in k after each pass for k = f:s:t The value of k in the last pass. A group of MATLAB Commands.. end.

The loop index variable can have any variable name but is usually i,j,k,m,n, however i,j should not be used if MATLAB is used with complex numbers. In the first pass k=f and the computer executed the commands between the for and end commands. Then the program goes back to the for command for the second pass. K obtains a new value equal to k=f+s and the commands between the for and end commands are executed with the new value. The process repeats itself until the last pass where k=t. Then the program does not go back to the for but continues with the commands that follow the end commands. For example 1:2:9, there are five loops and the corresponding values of k are 1,3,5,7 and 9. The increment s can be negative k=25:-5:10 gives four passes with k=25,20,15,10. If the increment s is omitted the default is 1. K=3:7 give k=3,4,5,6,7 If f=t the loop is executed once If f>t and s>0 or if f<t and s<0 the loop is not executed. If the values of of k,s,and t are such that k cannot be equal to t, then if s is positive, the last pass is the one where k has the largest value that is smaller than t (i.e. k=8:10:50 produces five passes with k=8:10:50 produces five passes with k=8,18,28,38,48. If s is negative, the last pass is the one where k has the smallest value that is larger than t. In the for command k can also be assigned a specific value. Example: for k=[7 9-1 3 3 5] The value of k should not be redefined within the loop. Each for command in a program must have an end command. The value of the loop index variable(k) is not displayed automatically. It is possible to display the value in each pass by typing k as one of the command is the loop. When the loop ends, the loop index variable(k) has the value that was last assigned to it. An example of a for-end loop is shown below. When this program is executed the loop is executed four times. The value of k in the four passes is k=1,4,7 and 10 which means that the values that are assigned to x in the passes are 1,16,49 and 100 respectively. Since a semicolon is not typed at the end of the second line, the value of x is displayed in the command window at each pass.

Colon operator: n=1:1:50; n goes from 1 to 50 in increments if 1 n=1:50; if the increment is omitted, 1 is assumed. n goes from 1 to 50 in steps of 1. n=1:2:50, no goes from 1 to 5 in steps of 2. Example: % This program calculates the sum of first fifty integers. tot=0; for number=1:50 tot=tot+number; end disp(tot) FOR Loop Rules: 1. The index must be a variable 2. If the expression is a scalar, the loop will be executed once. 3. If the expression is a row vector, the index will contain the next value in the vector in each loop. 4. When the loop is completed, the index contains the last value used. 5. If the colon operator is used to define the expression matrix using the following format: for k =initial : increment : limit then the no. of loops executed can be calculated from: limit-increment floor +1 increment Note: If the value is negative, the loop will not be executed.

Q. Write a for loop that will print the column of real numbers from 1.5 to 3.1 in steps of 0.2. for i = 1.5:0.2:3.1 disp(i) end Q Use a for-end loop in a script file to calculate the sum of the first n terms of the series: n k 1 1 2 k k k. Execute the script file for n=4 and n=20. n=input( Enter the number of terms ); S=0; for k=1:n S=S+(-1)^k*k/2^); end fprintf( The sum of the series is: %f,s) Q In the Command Window, write a for loop that will print the elements from a vector variable in sentence format. For example, if this is the vector: >> vec = [5.5 11 3.45]; this would be the result: Element 1 is 5.50. Element 2 is 11.00. Element 3 is 3.45. The for loop should work regardless of how many elements are in the vector. >> vec = [44 11 2 9 6]; >> for i = 1:length(vec) fprintf('element %d is %.2f\n',i,vec(i)) end Element 1 is 44.00 Element 2 is 11.00 Element 3 is 2.00 Element 4 is 9.00 Element 5 is 6.00 Note:conversion characters used in fprintf command. %d integer %f float %c single character %s string

Note on Matrices Q A vector is given by V=[5,17,-3,8,0,-7,12,15,20,-6,6,4,-7,16]. Write a script file that doubles the elements that are positive and are divisible by 3 or 5 and raises to the power of 3 the elements that are negative but greater than -5. This problem is solved by using a for-end loop that has an if-elseif-end conditional statement inside. The number of passes is equal to the number of elements in the vector. In each pass one element is checked by the conditional statement. The element is changed if it satisfies the conditions in the problem statement. A program in a script file that carries out the required operations is:

BREAK STATEMENT The BREAK statement can be used to exit a loop before it has been completed. Example: % This program shows use of break statement. If the denominator is zero % the program will exit the loop before it is completed. for i=1:5 den=input( Enter a value for denominator ) if den==0 disp( denominator is zero ) break end end WHILE LOOPS The while loop is a structure for repeating statements as long as a condition is true. while logical expression statements end

Example: We are making an investment of 100, which draws 10% in compound interest per year. This program will display the years and balance up to the point where initial investment is doubled.