Recap Function M-files Syntax of Function M-Files Comments Multiple Input and Output Functions.

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

Lecture 14 User-defined functions Function: concept, syntax, and examples © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Lecture 5.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
By Hrishikesh Gadre Session II Department of Mechanical Engineering Louisiana State University Engineering Equation Solver Tutorials.
Automating Tasks With Macros
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
MATLAB and Simulinklecture 31 To days Outline  Functions  Strings  Sparse Arrays  Cell Arrays  Structures  Exercises on this days topics.
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.
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.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
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.
Lecture 1: Introduction Lecture series based on the text: Essential MATLAB for Engineers and Scientists By Hahn & Valentine
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.
XP New Perspectives on Microsoft Access 2002 Tutorial 51 Microsoft Access 2002 Tutorial 5 – Enhancing a Table’s Design, and Creating Advanced Queries and.
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.
Moodle (Course Management Systems). Assignments 1 Assignments are a refreshingly simple method for collecting student work. They are a simple and flexible.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
Recap Graphic Window Edit Window Start Button Matrices in MATLAB Scalar Operations Order of Operations Array Operations Matrix Addition Matrix Multiplication.
 What is a formula in Excel?  A formula is statement written by the user to be calculated. Formulas can be as simple or as complex as the user wants.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
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.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
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.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Flow Control and Functions ● Script files ● If's and For's ● Basics of writing functions ● Checking input arguments ● Variable input arguments ● Output.
MAE 1202: AEROSPACE PRACTICUM An Introduction to MATLAB: Part 2 Mechanical and Aerospace Engineering Department Florida Institute of Technology Developed.
Introduction to Programming with RAPTOR
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Creating Graphical User Interfaces (GUI’s) with MATLAB By Jeffrey A. Webb OSU Gateway Coalition Member.
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
Lecture 5 1.What is a variable 2.What types of information are stored in a variable 3.Getting user input from the keyboard 1.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
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.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Recap Cubic Spline Interpolation Multidimensional Interpolation Curve Fitting Linear Regression Polynomial Regression The Polyval Function The Interactive.
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
Recap Functions with No input OR No output Determining The Number of Input and Output Arguments Local Variables Global Variables Creating ToolBox of Functions.
Matlab for Engineers Matlab Environment Chapter 2.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
Controlling Program Flow with Decision Structures.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Release Numbers MATLAB is updated regularly
Matlab Training Session 4: Control, Flow and Functions
Lecture 25.
Scripts & Functions Scripts and functions are contained in .m-files
User-Defined Functions
MATLAB: Structures and File I/O
User Defined Functions
Use of Mathematics using Technology (Maltlab)
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:

Recap Function M-files Syntax of Function M-Files Comments Multiple Input and Output Functions

Functions with No Input or No Output Although most functions need at least one input and return at least one output value, in some situations no inputs or outputs are required For example: consider this function, which draws a star in polar coordinates: function [] = star( ) theta = pi/2:0.8*pi:4.8*pi; r = ones(1,6); polar(theta,r) The square brackets on the first line indicate that the output of the function is an empty matrix (i.e., no value is returned) The empty parentheses tell us that no input is expected If, from the command window, you type star then no values are returned, but a figure window opens showing a star drawn in polar coordinates

Continued…. There are numerous built-in MATLAB functions that do not require any input. For example: A = clock returns the current time: A = 1.0e+003 * Columns 1 through Columns 5 through Also, A = pi returns the value of the mathematical constant p: A = However, if we try to set the MATLAB function tic equal to a variable name, an error statement is generated, because tic does not return an output value: A = tic ???Error using ==> tic Too many output arguments The tic function starts a timer going for later use in the toc function

Determining the Number of Input and Output Arguments There may be times when you want to know the number of input arguments or output values associated with a function MATLAB provides two built-in functions for this purpose The nargin function determines the number of input arguments in either a user-defined function or a built-in function The name of the function must be specified as a string, as, for example: in nargin('sin') ans =1 The remainder function, rem, requires two inputs; thus, nargin('rem') ans =2

Continued…. When nargin is used inside a user-defined function, it determines how many input arguments were actually entered This allows a function to have a variable number of inputs Recall graphing functions such as surf When surf has a single matrix input, a graph is created, using the matrix index numbers as the x – and y - coordinates. When there are three inputs, x, y, and z, the graph is based on the specified x- and y –values The nargin function allows the programmer to determine how to create the plot, based on the number of inputs

Continued…. The surf function is an example of a function with a variable number of inputs If we use nargin from the command window to determine the number of declared inputs, there isn’t one correct answer The nargin function returns a negative number to let us know that a variable number of inputs are possible: nargin('surf') ans = -1 The nargout function is similar to nargin, but it determines the number of outputs from a function: nargout('sin') ans = 1 The number of outputs is determined by how many matrices are returned, not how many values are in the matrix We know that size returns the number of rows and columnsin a matrix, so we might expect nargout to return 2 when applied to size. However, nargout('size') ans =1 returns only one matrix, which has just two elements, as for example, in x = 1:10; size(x) ans = 1 10

Continued…. An example of a function with multiple outputs is max : nargout('max') ans =2 When used inside a user-defined function, nargout determines how many outputs have been requested by the user Consider this example, in which we have rewritten the function to create a star: function A = star1( ) theta = pi/2:0.8*pi:4.8*pi; r = ones(1,6); polar(theta,r) if nargout==1 A = 'Twinkle twinkle little star'; end If we use nargout from the command window, as in nargout('star1') ans = 1 MATLAB tells us that one output is specified. If we call the function simply as star1 nothing is returned to the command window, although the plot is drawn If we callthe function by setting it equal to a variable, as in x = star1 x = Twinkle twinkle little star a value for x is returned, based on the if statement embedded in the function, which used nargout to determine the number of output values

Local Variables The variables used in function M-fi les are known as local variables The only way a function can communicate with the workspace is through input arguments and the output it returns Any variables defined within the function exist only for the function to use For example: consider the g function previously described: function output = g(x,y) % This function multiplies x and y together % x and y must be the same size matrices a = x.*y; output = a; The variables a, x, y, and output are local variables They can be used for additional calculations inside the g function, but they are not stored in the workspace To confi rm this, clear the workspace and the command window and then call the g function: clear, clc g(10,20) The function returns g(10,20) ans = 200

Continued…. Just as calculations performed in the command window or from a script M-fi le cannot access variables defined in functions, functions cannot access the variables defined in the workspace This means that functions must be completely self-contained: The only way they can get information from your program is through the input arguments, and the only way they can deliver information is through the function output Consider a function written to find the distance an object falls due to gravity: function result = distance(t) %This function calculates the distance a falling object %travels due to gravity g = 9.8 %meters per second squared result = 1/2*g*t.^2;

Continued…. The value of g must be included inside the function It doesn’t matter whether g has or has not been used in the main program How g is defined is hidden to the distance function unless g is specified inside the function Of course, you could also pass the value of g to the function as an input argument: function result = distance(g,t) %This function calculates the distance a falling object %travels due to gravity result = 1/2*g*t.^2;

Global Variables Unlike local variables, global variables are available to all parts of a computer program In general, it is a bad idea to define global variables However, MATLAB protects users from unintentionally using a global variable by requiring that it be identified both in the command-window environment and in the function that will use it Consider the distance function once again: function result = distance(t) %This function calculates the distance a falling object %travels due to gravity global G result = 1/2*G*t.^2; The global command alerts the function to look in the workspace for the value of G. G must also have been defined in the command window as a global variable: global G G = 9.8; This approach allows you to change the value of G without needing to redefine the distance function or providing the value of G as an input argument to the distance function

Creating ToolBox of Functions When a function is called in MATLAB, the program first looks in the current folder to see if the function is defined If it can’t find the function listed there, it starts down a predefined search path, looking for a fi le with the function name To view the path the program takes as it looks for files, select File -> Set Path from the menu bar or type pathtool in the command window

Continued…. As more and more functions are created to use in programming, it may be needed to modify the path to look in a directory where personal tools have been stored. For example: suppose you have stored the degrees-to- radians and radians-to-degrees functions created in a directory called My_functions. You can add this directory to the path by selecting Add Folder from the list of option buttons in the Set Path dialog window. You’ll be prompted to either supply the folder location or browse to find it (shown in next slide)

Continued…. MATLAB now first looks into the current folder for function definitions and then works down the modified search path

Continued…. Once a folder is added to the path, the change applies only to the current MATLAB session, unless changes are saved permanently Clearly, permanent changes should never make to a public computer However, if someone else has made changes you wish to reverse, you can select the default button to return the search path to its original settings The path tool allows to change the MATLAB search path interactively; however, the addpath function allows to insert the logic to add a search path to any MATLAB program Consult help addpath if you wish to modify the path in this way. MATLAB provides access to numerous toolboxes developed at The MathWorks or by the user community

Anonymous Functions and Function Handles Normally, if there is trouble of creating a function, you will want to store it for use in other programming projects However, MATLAB includes a simpler kind of function, called an anonymous function Anonymous functions are defined in the command window or in a script M- file and are available—much as are variable names—only until the workspace is cleared To create an anonymous function, consider the following example: ln log(x) symbol alerts MATLAB® that ln is a function. Immediately following symbol, the input to the function is listed in parentheses. Finally, the function is defined. The function name appears in the variable window, listed as a function_handle:

Continued…. Anonymous functions can be used like any other function—for example, ln(10) ans = Anonymous functions can be saved as.mat files, just like any variable, and can be restored with the load command For example: to save the anonymous function ln, type: save my_ln_function ln A file named my_ln_function.mat is created, which contains the anonymous ln function Once the workspace is cleared, the ln function no longer exists, but it can be reloaded from the.mat file load my_ln_function It is possible to assign a function handle to any M-fi le function The command distance_handle distance(t) assigns the handle distance_handle to the distance function Anonymous functions and the related function handles are useful in functions that require other functions as input

Function Functions MATLAB’s function functions have an odd, but descriptive name They are functions that require other functions as input One example of a MATLAB built-in function function is the function plot, fplot. This function requires two inputs: a function or a function handle, and a range over which to plot We can demonstrate the use of fplot with the function handle ln, defined as ln log(x) The function handle can now be used as input to the fplot function: fplot(ln,[0.1, 10]) The result is shown in next slide We could also use the fplot function without the function handle We just need to insert the function syntax directly, as a string: fplot('log(x)',[0.1, 10]) The advantage to using function handles isn’t obvious from this example, but consider instead this anonymous function describing a particular fi fth- order polynomial: poly5 -5*x.^ *x.^4 + 3*x.^3 + 20*x.^2 - x + 5;

Function handles can be used as input to a function functions, such as fplot

Continued…. Entering the equation directly into the fplot function would be awkward Using the function handle is considerably simpler. fplot(poly5,[-30,90]) The results are shown in next slide’s figure A wide variety of MATLAB functions accept function handles as input For example: the fzero function finds the value of x where f ( x ) is equal to 0. It accepts a function handle and a rough guess for x. We see that our fifth-order polynomial probably has a zero between 75 and 85, so a rough guess for the zero point might be x = 75. fzero(poly5,75) ans =

Subfunctions More complicated functions can be created by grouping functions together in a single file as subfunctions These subfunctions can be called only from the primary function, so they have limited utility Subfunctions can be used to modularize code and to make the primary function easier to read Each MATLAB function M-fi le has one primary function The name of the M-file must be the same as the primary function name Thus, the primary function stored in the M-file my_function.m must be named my_function Subfunctions are added after the primary function, and can have any legitimate MATLAB variable name

Continued…. Figure shows a very simple example of a function that both adds and subtracts two vectors The primary function is named subfunction_demo The file includes two subfunctions: add and subtract

Continued…. In the editing window that the contents of each function are identified with a gray bracket Each code section can be either collapsed or expanded, to make the contents easier to read, by clicking on the + or - sign included with the bracket MATLAB uses the term “folding” for this functionality Folding can also be accessed from the “Text” menu on the menu bar

Example

Solution

Continued…. The primary function has no input and no output To execute the primary function, type the function name at the command prompt: sample_homework or select the save and run icon When the primary function executes, it calls the subfunctions, and the results are displayed in the command window, as follows: Problem 1 The squares of the input values are listed below Problem 2 The percent cold work is ans = Problem 3 The change in potential energy is ans =

Continued…. In this example, the four functions are listed sequentially An alternate approach is to list the subfunction within the primary function, usually placed near the portion of the code from which it is called. This is called nesting When functions are nested, we need to indicate the end of each individual function with the end command