BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.

Slides:



Advertisements
Similar presentations
2.1 Program Construction In Java
Advertisements

Introduction to Macromedia Director 8.5 – Lingo
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Methods Java 5.1 A quick overview of methods
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Lecture 4 Structure plan Program design process Program design process Basic elements of code: Basic elements of code: –Input (assignment of variables)
E ngineering College of San Jose State University Engr.10 1 JKA & KY.
Slides 2c: Using Spreadsheets for Modeling - Excel Concepts (Updated 1/19/2005) There are several reasons for the popularity of spreadsheets: –Data are.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
3-2 What are relational operators and logical values? How to use the input and disp functions. Learn to use if, if-else and else-if conditional statements.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Computer Science 1620 Loops.
Lecture 6 MATLAB functions Basics of Built-in Functions, Help Feature, Elementary Functions (e.g., Polynomials, Trigonometric Functions), Data Analysis,
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Computer Science 1620 Programming & Problem Solving.
Complexity (Running Time)
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Introduction to Matlab. Entering Commands Constants and Functions >> pi ans = >> eps ans = e-016 >> sin(pi/2) ans = 1 >> log(1000) ans =
Fundamentals of Python: From First Programs Through Data Structures
1 CS101 Introduction to Computing Lecture 35 Mathematical Methods (Web Development Lecture 12)
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Computer Literacy BASICS
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
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.
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 3”
BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.
Essential MATLAB® for Engineers and Scientists
Programming for Artists ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 8 Fall 2010.
Chapter 5: Control Structures II (Repetition)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) MATH Functions in C Language.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Recap Graphic Window Edit Window Start Button Matrices in MATLAB Scalar Operations Order of Operations Array Operations Matrix Addition Matrix Multiplication.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 6”
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.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
30/10/ Iteration Loops Do While (condition is true) … Loop.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Recap Sum and Product Functions Matrix Size Function Variance and Standard Deviation Random Numbers Complex Numbers.
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.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
CS1109 L AB 3 July 3rd. R OAD M AP Homework submission Review How to use function and scripts While-end Finish last exercise Lab 2 Challenge questions.
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.
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
MATLAB Constants, Variables & Expression Nafees Ahmed Asstt. Professor, EE Deptt DIT, DehraDun.
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
Computer Simulation Lab
MATLAB DENC 2533 ECADD LAB 9.
Formatted and Unformatted Input/Output Functions
Introduction to Matlab
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Computer Simulation Lab
Electrical and Computer Engineering Department SUNY – New Paltz
Presentation transcript:

BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists

Ch.4: MATLAB functions & *data import-export utilities The objectives of this chapter are: 1. To enable you to become familiar with some of the more common MATLAB functions. 2. To introduce you briefly to ways of importing and exporting data in and out of the MATLAB workspace using: - The load and save commands. - The Import Wizard. - The low-level file input/output (I/O) functions. We will only discuss the first objective.

Cont. More interesting problems in science and engineering are likely to involve special mathematical functions like sines, cosines, logarithms, etc. MATLAB comes with a large collection of such functions; we have seen some of them already. This chapter introduces you to the more common functions available in MATLAB.

4.1 Some common functions Use helpwin at the command line to see a list of categories of functions, with links to descriptions of the functions. Note that if the argument of a function is an array, the function is applied element by element to all the values in the array, e.g. - sqrt([ ]) % returens:

Cont. One way to examine these functions is to plot them. For example, do the following exercise for all functions of the assigned variable x, as illustrated next. - x = -1:.1:1; - plot(x,abs(x),’o’) You should get an illustration that looks like a V. abs(x): absolute value of x.

Cont. acos(x): arc cosine (inverse cosine) of x between 0 and π. acosh(x): inverse hyperbolic cosine of x, - i.e. asin(x): arc sine (inverse sine) of x between −π/ 2 and π/ 2. asinh(x): inverse hyperbolic sine of x, - i.e.

Cont. atan(x): arc tangent of x between −π/2 and π/2. atan2(y, x): arc tangent of y/x between −π and π. atanh(x): inverse hyperbolic tangent of x, - i.e. ceil(x): smallest integer which exceeds x, i.e. rounds up to nearest integer, e.g. ceil(-3.9) returns -3, ceil(3.9) returns 4. cumsum(x): cumulative sum of the elements of x, - e.g. cumsum(1:4) returns [ ].

Cont. date: date in a string in dd-mmm-yyyy format, - e.g. 02-Feb exp(x): value of the exponential function e x. fix(x): rounds to the nearest integer towards zero, - e.g. fix(-3.9) returns -3, fix(3.9) returns 3. floor(x): largest integer not exceeding x, i.e. rounds down to nearest integer, - e.g. floor(-3.9) returns -4, floor(3.9) returns 3. length(x): number of elements of vector x.

Cont. max(x): maximum element of vector x. mean(x): mean value of elements of vector x. min(x): minimum element of vector x. pow2(x): 2 x. rem(x, y): remainder when x is divided by y, - e.g. rem(19, 5) returns 4.

Cont. fix and rem are useful for converting smaller units to larger ones, e.g. inches to feet and inches (one foot = 12 inches). The following statements convert 40 inches this way: - feet = fix(40/12) - inches = rem(40, 12)

Ch.8: Loops The objectives of this chapter are to enable you to learn to: - Program (or code) determinate loops with for. - Program (or code) indeterminate loops with while. In Chapter 2 we introduced the powerful for statement, which is used to repeat a block of statements a fixed number of times.

Cont. This type of structure, where the number of repetitions must be determined in advance, is sometimes called determinate repetition. However, it often happens that the condition to end a loop is only satisfied during the execution of the loop itself. Such a structure is called indeterminate. This chapter is mainly about indeterminate loops, but to emphasize the difference between the two types of repetition we will first look at some more examples of for loops.

8.1 Determinate repetition with for The binomial coefficient is widely used in mathematics and statistics. It is defined as the number of ways of choosing r objects out of n without regard to order, and is given by - 1. If this form is used, the factorials can get very big, causing an overflow. But a little thought reveals we can simplify Equation as follows: - 2.

Cont. E.g. Solving the previous example using for loop: - ncr = 1; - n = 10 - r = 3 - for k = 1:r - ncr = ncr * (n - k + 1) / k; - end - disp( ncr )

8.2 Indeterminate repetition with while Determinate loops all have in common the fact that you can work out in principle exactly how many repetitions are required before the loop starts. But in the next example, there is no way in principle of working out the number of repeats, so a different structure is needed.

8.2.1 A guessing game The problem is easy to state. MATLAB ‘thinks’ of an integer between 1 and 10 (i.e. generates one at random). You have to guess it. If your guess is too high or too low, the script must say so. If your guess is correct, a message of congratulations must be displayed.

Cont. A little more thought is required here, so a structure plan might be helpful: - Generate random integer - Ask user for guess - While guess is wrong: If guess is too low Tell him it is too low Otherwise Tell him it is too high Ask user for new guess - Stop

Cont. Here is the script: matnum = floor(10 * rand + 1); guess = input( ’Your guess please: ’ ); while guess ˜= matnum if guess > matnum disp( ’Too high’ ) else disp( ’Too low’ ) end; guess = input( ’Your next guess please: ’ ); end disp (‘Congratulations ‘)

Cont. Try it out a few times. Note that the while loop repeats as long as matnum is not equal to guess. There is no way in principle of knowing how many loops will be needed before the user guesses correctly. The problem is truly indeterminate. Note that guess has to be input in two places: firstly to get the while loop going, and secondly during the execution of the while.

8.2.2 The while statement In general the while statement looks like this: - while condition statements end The while construct repeats statements WHILE its condition remains true. The condition is tested each time BEFORE statements are repeated. Recall that a vector condition is considered true only if all its elements are non-zero. The command-line form of while is: - while condition statements, end

8.2.3 Doubling time of an investment Suppose we have invested some money which draws 10 percent interest per year, compounded. We would like to know how long it takes for the investment to double. More specifically, we want a statement of the account each year, until the balance has doubled.

Cont. The English statement of the problem hints heavily that we should use an indeterminate loop with the following structure plan: 1. Initialize balance, year, interest rate 2. Display headings 3. Repeat Update balance according to interest rate Display year, balance until balance exceeds twice original balance 4. Stop.

Cont. A program to implement this plan would be - a = 1000; - r = 0.1; - bal = a; - year = 0; - disp( ’Year Balance’ ) - while bal < 2 * a - bal = bal + r * bal; - year = year + 1; - disp( [year bal] ) - end

Cont. Note that when the last loop has been completed, the condition to repeat is false for the first time, since the new balance ($ ) is more than $2000. Note also that a determinate for loop cannot be used here because we don’t know how many loops are going to be needed. If you want to write the new balance only while it is less than $2000, all that has to be done is to move the statement: disp( [year bal] ) until it is the first statement in the while loop. Note that the initial balance of $1000 is displayed now.

8.2.4 Prime numbers A number is prime if it is not an exact multiple of any other number except itself and 1. - i.e. if it has no factors except itself and 1. Suppose P is the number to be tested. See if any numbers N can be found that divide into P without remainder. If there are none, P is prime. Which numbers N should we try? Well, we can speed things up by restricting P to odd numbers, so we only have to try odd divisors N. When do we stop testing? When N=P ? No, we can stop a lot sooner. In fact, we can stop once N reaches

Cont. Since if there is a factor greater than there must be a corresponding one less than which we would have found. The structure plan is as follows: 1. Input P 2. Initialize N to 3 3. Find remainder R when P is divided by N 4. While R 0 and N < repeat: Increase N by 2 Find R when P is divided by N

Cont. 5. If R 0 then P is prime Else P is not prime 6. Stop Note that there are two conditions under which the loop may stop. Consequently, an if is required after completion of the loop to determine which condition stopped it. See if you can write the script. Then try it out on the following numbers: (not prime), (prime) and (prime).

8.2.7 Menus Try the following program, which sets up a menu window: - k = 0; - while k ˜= 3 - k = menu( ’Click on your option’, ’Do this’,... ’Do that’, ’Quit’ ); - if k == 1 - disp( ’Do this... press any key to continue...’ ) - Pause - elseif k == 2 - disp( ’Do that... press any key to continue...’ ) - Pause - end - end;

Cont. Note: 1. The menu function enables you to set up a menu of choices for a user. 2. menu takes only string arguments. The first one is the title of the menu. The second and subsequent strings are the choices available to the user. 3. The value returned by menu ( k here) numbers the user’s choices.

Cont. 4. Since one has no idea how many choices the user will make, menu is properly enclosed in an indeterminate while loop. The loop continues to present the menu until the last option (in this example) is selected. 5. You can design much more sophisticated menu-driven applications with the MATLAB GUIDE (Graphical User Interface Development Environment).