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.

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

Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
CMPS 1371 Introduction to Computing for Engineers
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Programming with MATLAB
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
General Computer Science for Engineers CISC 106 Lecture 04 Roger Craig Computer and Information Sciences 9/11/2009.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
General Computer Science for Engineers CISC 106 Lecture 08 Dr. John Cavazos Computer and Information Sciences 2/27/2009.
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Fundamentals of Python: From First Programs Through Data Structures
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files called M- files. M-files are.
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.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
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.
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
ENGR 1320 Final Review - Programming Major Topics: – Functions and Scripts – Vector and Matrix Operations in Matlab Dot product Cross product – Plotting.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
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.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Linux Operations and Administration
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.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
Introduction to Matlab Module #2 Page 1 Introduction to Matlab Module #2 – Arrays Topics 1.Numeric arrays (creation, addressing, sizes) 2.Element-by-Element.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Matlab for Engineers Logical Functions and Control Structures Chapter 8.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing 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.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
CMPS 1371 Introduction to Computing for Engineers CHARACTER STRINGS.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
Finishing up Chapter 5. Will this code enter the if statement? G=[30,55,10] if G
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
INTRODUCTION TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in.
EEE 161 Applied Electromagnetics
Repetition Structures Chapter 9
Matlab Training Session 4: Control, Flow and Functions
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB: Structures and File I/O
User Defined Functions
Conditional Statements
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Use of Mathematics using Technology (Maltlab)
T. Jumana Abu Shmais – AOU - Riyadh
Iteration: Beyond the Basic PERFORM
Logical Operations In Matlab.
Loop Statements & Vectorizing Code
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.
Loop Statements & Vectorizing Code
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

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 current directory

User-defined functions must start with a function definition line The line contains… The word function A variable that defines the function output A function name A variable used for the input argument function output = poly(x) xz

A simple function In the new version, the file name could be different from the function name.

The function is available from the command window or from other M-file programs

Comments You should comment functions liberally, just as you would any computer code The comment lines immediately after the first line are returned when you query the help function

Functions with Multiple Inputs A user defined function with multiple inputs

Functions with Multiple Outputs This function return 3 output values If you don’t ask for all three results, the program just returns the first value

Local Variables Variables defined in an M-file function, only have meaning inside that program if set x=1 in the command window, it is not equal to 1 in the function If set y=2 in a function, it is not equal to 2 in the workspace window The only way to communicate between functions and the workspace, is through the function input and output arguments

User Defined Input To this point we have “hard coded” the values of variables into our M-file programs The input function allows us to prompt the user to enter a value

The input function is used in an M-file program to prompt the user to enter a value The prompt is displayed in the command window

Input accepts a variety of data Scalars Matrices enter inside square brackets Character strings enter inside single quotes Or… specify string input with ‘s’

Run this program twice – once with numeric input and once with character input

Indicates that the input should be interpreted as a string

Output Options Enter the name of a variable Use the disp function Use the fprintf function

disp The display (disp) function can be used to display the contents of a matrix without printing the matrix name

The disp function can also be used to display a string

You can combine disp functions to create meaningful output from an M-file program, but the result of each disp function is on a separate line.

Use the num2str(x) function to change numeric information to a string Since the disp function only takes one input, you must combine arrays to make more complicated output disp(['The values in the x array are: ' num2str(x)])

Structures Sequence Selection Repetition SequenceSelectionRepetition (Loop)

Selection and Repetition structures require comparisons to work Relational operators make those comparisons Logical operators allow us to combine the comparisons

Relational Operators < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not equal to

Logical Operators & and ~ not | or xor exclusive or

Selection Structures find A family of if structures

find The find command searches a matrix and identifies which elements in that matrix meet a given criteria.

For example… The US Naval Academy requires applicants to be at least 66” tall Consider this list of applicant heights 63”, 67”, 65”, 72”, 69”, 78”, 75” Which applicants meet the criteria?

The find function returns the index number for elements that meet a criteria

index numbers element values

find used with a 2D matrix x =[1 2 3; ; ; 8 3 1] element = find(x > 9) [row, column] = find(x > 9) Returns a single element number Returns the row and column designation of an element

Simple if if comparison statements end For example…. if G<50 count = count +1; disp(G); end

If statements Easy to interpret for scalars What does an if statement mean if the comparison includes a matrix? The comparison is only true if it is true for every member of the array G=[30,55,10] if G<50 count = count +1; disp(G); end The code inside the if statement is not executed, because the comparison is not true!!

The if/else structure The simple if triggers the execution of a block of code if a condition is true If it is false that block of code is skipped, and the program continues without doing anything What if instead you want to execute an alternate set of code if the condition is false?

Use an if structure to calculate a natural log Check to see if the input is positive If it is, calculate the natural log If it isn’t, send an error message to the screen

The if/else/elseif structure Use the elseif for multiple selection criteria For example Write a program to determine if an applicant is eligible to drive

Repetition Structures - Loops Loops are used when you need to repeat a set of instructions multiple times MATLAB supports two types of loops for while

When to use loops In general loops are best used with scalars Many of the problems you may want to attempt with loops can be better solved by vectorizing your code or with MATLAB’s logical functions such as find

For Loops for index = [matrix] commands to be executed end The loop starts with a for statement, and ends with the word end. The first line in the loop defines the number of times the loops will repeat, using an index number. The loop is executed once for each element of the index matrix identified in the first line The index of a for loop must be a variable.

Here’s a simple example In this case k is the index – the loop is repeated once for each value of k the index can be defined using any of the techniques we’ve learned

Here’s a simple example In this case k is the index – the loop is repeated once for each value of k the index can be defined using any of the techniques we’ve learned

While Loops while criterion commands to be executed end While loops are very similar to for loops. The big difference is the way MATLAB decides how many times to repeat the loop. While loops continue until some criterion is met.

This loop creates the matrix a, one element at a time

Improving the Efficiency of Loops In general, using a for loop (or a while loop) is less efficient in MATLAB than using array operations.

The amount of time it takes to run this code will depend on your computer Here’s an example. This code creates a 40,000 element matrix of ones, then multiplies each element in the matrix by pi These two lines of code start a timer to measure the elapsed time required to run the lines of MATLAB code between them

This code accomplishes the same thing with a for loop