Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Slides:



Advertisements
Similar presentations
Chapter 11 Introduction to Programming in C
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Flow Charts, Loop Structures
Programming with MATLAB
ITEC113 Algorithms and Programming Techniques
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
General Computer Science for Engineers CISC 106 Lecture 04 Roger Craig Computer and Information Sciences 9/11/2009.
General Computer Science for Engineers CISC 106 Lecture 07 Dr. John Cavazos Computer and Information Sciences 2/25/2009.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Program Design and Development
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Input/Output Functions Selim Aksoy Bilkent University Department of Computer Engineering
Guide To UNIX Using Linux Third Edition
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Matrix Mathematics in MATLAB and Excel
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Chapter 7 Matrix Mathematics Matrix Operations Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
1 Chapter 1 MATLAB Primer This introductory chapter is relatively short and has as its main objective the introduction of MATLAB ® to the reader. This.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
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.
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.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
1 Week 2: Variables and Assignment Statements READING: 1.4 – 1.6 EECS Introduction to Computing for the Physical Sciences.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Working with Arrays in MATLAB
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
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.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
1 CS1371 Introduction to Computing for Engineers Control Statements 9/4/2003.
MATLAB for Engineers, by Holly Moore. ISBN © 2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
1 Lecture 4 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
CMPS 1371 Introduction to Computing for Engineers CHARACTER STRINGS.
Controlling Program Flow with Decision Structures.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Chapter 2 Excel Fundamentals Logical IF (Decision) Statements Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 4 MATLAB Programming MATLAB Troubleshooting Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Chapter 1 Computing Tools Variables, Scalars, and Arrays Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 2 Excel Fundamentals
© 2016 Pearson Education, Ltd. All rights reserved.
Control Statements in Matlab
Chapter 4 MATLAB Programming
Chapter 4 MATLAB Programming
Other Kinds of Arrays Chapter 11
T. Jumana Abu Shmais – AOU - Riyadh
Iteration: Beyond the Basic PERFORM
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
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.
Presentation transcript:

Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Combining Loops and Logic Complex programs usually contain a both loops and logical statements to control the sequence of calculations As an example, let’s consider this example: We want to create an identity matrix (a square array with all ones as diagonal elements, zeros as off- diagonal elements) for a given size. For size = 3, our matrix would be: Engineering Computation: An Introduction Using MATLAB and Excel

Example There is a built-in MATLAB command “eye” that creates an identity matrix, but we will ignore that for this example We will call the matrix A, so we need to define each element A(m,n) where m and n both range from 1 to the specified size This will require two nested for loops For each element, a conditional statement is required: if m = n, then A(m,n) = 1, else A(m,n) = 0 Engineering Computation: An Introduction Using MATLAB and Excel

Example Can you de-scramble these lines of code to create an identity matrix and print it to the screen? Engineering Computation: An Introduction Using MATLAB and Excel A(m,n) = 0; for m = 1:Size end Size = 10; A A(m,n) = 1; else end if m == n end for n = 1:Size

Flow Chart Engineering Computation: An Introduction Using MATLAB and Excel

Solution Engineering Computation: An Introduction Using MATLAB and Excel Size = 10; for m = 1:Size for n = 1: Size if m == n A(m,n) = 1; else A(m,n) = 0; end A

Example Engineering Computation: An Introduction Using MATLAB and Excel

Example Let’s set the Size to 3 and repeat: No change! What happened? Engineering Computation: An Introduction Using MATLAB and Excel

Example A was stored as a a 10 X 10 matrix in memory before the m-file was modified When the new file was executed, the elements of A up to (3,3) were overwritten; the rest were unchanged Good practice to clear your variables (especially arrays) at the beginning of an m-file: Engineering Computation: An Introduction Using MATLAB and Excel

Example Now it works: Engineering Computation: An Introduction Using MATLAB and Excel

Example (Example 4.2) In many textbook problems, a triangle is encountered: Note that the hypotenuse (5) is a perfect square: an integer that is the square root of another integer (25) Many calculations are made simple for this configuration: cos θ = 4/5; sin θ = 3/5, etc. θ 3 4 5

Problem Description Can we find the other perfect squares for integer side lengths x and y from 1 to 25? h = hypotenuse Engineering Computation: An Introduction Using MATLAB and Excel θ y x h

Program Planning We will need to use two nested loops, since we have two independent variables: x and y Things to consider: – How will we identify perfect squares mathematically? – Do we want to store the perfect squares that we find, and/or do we want to print them to the screen or a file? – Do we want to count the number of perfect square combinations found? Engineering Computation: An Introduction Using MATLAB and Excel

Begin Flow Chart with Loop Statements How do we determine if h is an integer? Consider the MATLAB function floor: >> help floor FLOOR Round towards minus infinity. FLOOR(X) rounds the elements of X to the nearest integers towards minus infinity. Engineering Computation: An Introduction Using MATLAB and Excel for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2)

Check for Perfect Square We can compare h and floor(h) directly in an if statement: if h == floor(h) If this statement is true, then we will print the values of x, y, and h to the screen If it is false, then we will do nothing Engineering Computation: An Introduction Using MATLAB and Excel

MATLAB Code for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); What type of conditional statement do we need? if if-else if-elseif Engineering Computation: An Introduction Using MATLAB and Excel

MATLAB Code A simple if statement works here – we either do the next steps or we skip them for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) x y h end Engineering Computation: An Introduction Using MATLAB and Excel

MATLAB Code Close both loops with end statements for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) x y h end Engineering Computation: An Introduction Using MATLAB and Excel

Results Save file as “PerSquares” and run: >> PerSquares x = 3 y = 4 h = 5 x = 4 y = 3 h = 5 (Screen output continues for many lines) Engineering Computation: An Introduction Using MATLAB and Excel

Add Formatting to Output for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) end More about the fprintf command later Engineering Computation: An Introduction Using MATLAB and Excel

Results >> PerSquares >> How would we add a counter to report the number of combinations found? How do we eliminate duplicates? (such as 3, 4, 5; 4, 3, 5) Engineering Computation: An Introduction Using MATLAB and Excel

Counter Added m = 0; for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) m = m + 1; end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel

Eliminating Duplicates The first time though the x-loop, x = 1 and y = 1:25: x = 1 y = 1,2,3,4….25 The second time though the x-loop, x = 2 and y = 1:25: x = 2 y = 1,2,3,4….25 But since we have already looked at the combination x = 1, y = 2, we do not want to look at x = 2, y = 1 Engineering Computation: An Introduction Using MATLAB and Excel

Eliminating Duplicates If we start the y-loop at 2 when x = 2: x = 2 y = 2,3,4,5….25 And start the y-loop at 3 when x = 3: x = 3 y = 3,4,5,6….25 And similar for the other values of x, then we have eliminated duplicate combinations Engineering Computation: An Introduction Using MATLAB and Excel

y-Loop Adjusted m = 0; for x = 1:25 for y = x:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) m = m + 1; end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel

Results >> PerSquares Combinations found = 11 >> For you to think about: How would we eliminate combinations that are multiples of other combinations? (Example: 6, 8, 10 is a multiple of 3, 4, 5 – forms a similar triangle) Engineering Computation: An Introduction Using MATLAB and Excel

The fprintf Command This command writes formatted output to the screen The format of the command is: fprintf(fid, ’Text to be written, including conversion specifications for any variables to be printed’, variables) The file ID (fid) is omitted for output to the screen Conversion specifications are instructions for how the variables are to be formatted, inserted at the points where the variables are to be written Engineering Computation: An Introduction Using MATLAB and Excel

Conversion Specifications Conversion specifications begin with a % symbol Next comes the number of digits and decimal places Last is designator of format type. Most common are: f = fixed number of decimal places E or e = exponential notation i = integer Engineering Computation: An Introduction Using MATLAB and Excel

Examples >> fprintf('Pi = %8.3f',pi) Pi = Engineering Computation: An Introduction Using MATLAB and Excel Text to be written to the screen, including the conversion specification for the variable (pi) pi is output over 8 spaces, including 3 decimal places

Examples >> fprintf('Pi = %e',pi) Pi = e+000 Engineering Computation: An Introduction Using MATLAB and Excel Note that the number of digits and the number of decimal places are optional pi is output in exponential notation, with the number of digits corresponding to the default “short” format

Examples >> fprintf('\nPi = %.4f\n',pi) Pi = >> Engineering Computation: An Introduction Using MATLAB and Excel The characters \n within the output string start a new line pi is output to 4 decimal places

Examples >> m = 12; >> fprintf('\n\nThe value of m is %i\n\n',m) The value of m is 12 >> Engineering Computation: An Introduction Using MATLAB and Excel m is output as an integer

Writing to a File Before writing to a file, you must first open a file and assign it to “fid” (file ID): Example: fid = fopen('amtable','wt'); 'wt' indicates write access; text file format. If the file does not exist, it will be created. If it already exists, its contents will be overwritten 'at' instead of 'wt' indicates that an existing file will be appended – the new results will be added to the end of an existing file Engineering Computation: An Introduction Using MATLAB and Excel

Modifications to “PerSquares” File: m = 0; fid = fopen('output.txt','wt'); fprintf(fid,' x y h\n'); fprintf(fid,' === === ===\n'); for x = 1:25 for y = x:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf(fid,'%5i %5i %5i\n',x,y,h); m = m + 1; end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel New file “output.txt” opened for write access Column headers written to file Integer triangles written to file Number of triangles found written to screen

Output The table is now printed to the file “output,” which can be opened in Word or Notepad, or imported into Excel Engineering Computation: An Introduction Using MATLAB and Excel