MATLAB Functions. function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m)



Similar documents
Lecture 2 Mathcad Basics

Beginner s Matlab Tutorial

How to test and debug an ASP.NET application

Introduction. Chapter 1

MATLAB Programming. Problem 1: Sequential

CD-ROM Appendix E: Matlab

Tutorial Program. 1. Basics

Curve Fitting, Loglog Plots, and Semilog Plots 1

LS.6 Solution Matrices

MATLAB Tutorial. Chapter 6. Writing and calling functions

Excel Basics By Tom Peters & Laura Spielman

Introduction to Matlab

FIRST STEPS WITH SCILAB

Lab 1: Introduction to C, ASCII ART and the Linux Command Line Environment

Creating trouble-free numbering in Microsoft Word

Financial Econometrics MFE MATLAB Introduction. Kevin Sheppard University of Oxford

MATLAB Basics MATLAB numbers and numeric formats

Excel macros made easy

Create a New Database in Access 2010

Appendix K Introduction to Microsoft Visual C++ 6.0

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

Summary of important mathematical operations and formulas (from first tutorial):

There are six different windows that can be opened when using SPSS. The following will give a description of each of them.

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison

Word 2010: Mail Merge to with Attachments

Create a report with formatting, headings, page numbers and table of contents

Simple Programming in MATLAB. Plotting a graph using MATLAB involves three steps:

Getting Started with Excel Table of Contents

Excel 2003 A Beginners Guide

Scatter Plots with Error Bars

Setting Up Outlook on Workstation to Capture s

Tutorial Microsoft Office Excel 2003

Hypercosm. Studio.

Excel 2007 A Beginners Guide

PGR Computing Programming Skills

For Introduction to Java Programming, 5E By Y. Daniel Liang

General Framework for an Iterative Solution of Ax b. Jacobi s Method

Quick Tour of Mathcad and Examples

Tips and Tricks SAGE ACCPAC INTELLIGENCE

Using Karel with Eclipse

CS106B Handout #5P Winter January 14, 2008

Microsoft Migrating to Word 2010 from Word 2003

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

MatLab Basics. Now, press return to see what Matlab has stored as your variable x. You should see:

Lecture 3: Finding integer solutions to systems of linear equations

CNC Transfer. Operating Manual

eportfolio Student Guide

Appendix: Tutorial Introduction to MATLAB

What is Microsoft Excel?

Tutorial for the TI-89 Titanium Calculator

To launch the Microsoft Excel program, locate the Microsoft Excel icon, and double click.

EXCEL SOLVER TUTORIAL

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial VI

Learning Objective. Purpose The purpose of this activity is to give you the opportunity to learn how to set up a database and upload data.

JAVS Scheduled Publishing. Installation/Configuration... 4 Manual Operation... 6 Automating Scheduled Publishing... 7 Windows XP... 7 Windows 7...

You must have at least Editor access to your own mail database to run archiving.

Intermediate PowerPoint

Creating tables of contents and figures in Word 2013

6. Control Structures

BIGPOND ONLINE STORAGE USER GUIDE Issue August 2005

Using SPSS, Chapter 2: Descriptive Statistics

Basic Formulas in Excel. Why use cell names in formulas instead of actual numbers?

Microsoft Office. Mail Merge in Microsoft Word

SECTION 5: Finalizing Your Workbook

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

8.1. Cramer s Rule for Solving Simultaneous Linear Equations. Introduction. Prerequisites. Learning Outcomes. Learning Style

During the process of creating ColorSwitch, you will learn how to do these tasks:

GUI Input and Output. Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University

SSH Connections MACs the MAC XTerm application can be used to create an ssh connection, no utility is needed.

Solving Systems of Linear Equations Using Matrices

Many home and small office networks exist for no

MS Excel Template Building and Mapping for Neat 5

Excel & Visual Basic for Applications (VBA)

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Important Tips when using Ad Hoc

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Data Visualization. Prepared by Francisco Olivera, Ph.D., Srikanth Koka Department of Civil Engineering Texas A&M University February 2004

Calibration and Linear Regression Analysis: A Self-Guided Tutorial

Introduction to Microsoft Excel 2010

Creating a table of contents quickly in Word

Business Portal for Microsoft Dynamics GP. Key Performance Indicators Release 10.0

SQL Server 2005: Report Builder

Customizing forms and writing QuickBooks Letters

LESSON 7: IMPORTING AND VECTORIZING A BITMAP IMAGE

Downloading Your Financial Statements to Excel

Migrating to Excel 2010 from Excel Excel - Microsoft Office 1 of 1

3. Add and delete a cover page...7 Add a cover page... 7 Delete a cover page... 7

Project 2: Bejeweled

Online Sharing User Manual

Lecture 4: Writing shell scripts

Using Excel for Business Analysis: A Guide to Financial Modelling Fundamentals

Introduction to the UNIX Operating System and Open Windows Desktop Environment

After you complete the survey, compare what you saw on the survey to the actual questions listed below:

Microsoft Migrating to PowerPoint 2010 from PowerPoint 2003

Installing and using XAMPP with NetBeans PHP

Business Portal for Microsoft Dynamics GP Key Performance Indicators

Infinite Campus Ad Hoc Reporting Basics

Beginning to Program Python

Data Analysis Tools. Tools for Summarizing Data

Business Portal for Microsoft Dynamics GP User s Guide Release 5.1

Transcription:

MATLAB Functions What is a MATLAB function? A MATLAB function is a MATLAB program that performs a sequence of operations specified in a text file (called an m-file because it must be saved with a file extension of *.m). A function accepts one or more MATLAB variables as inputs, operates on them in some way, and then returns one or more MATLAB variables as outputs and may also generate plots, etc. (sometimes a function doesn t return any output variables but instead just generates plots, etc.). How do I Create a new MATLAB function? Since an m-file is nothing more than a text file it can be created using any text editor however, MATLAB provides its own editor that provides some particular features that are useful when writing/editing functions. To open a new m-file: In the MATLAB command window, go to FILE on the toolbar, select NEW, then select M-FILE. This opens the MATLAB editor/debugger and gives an empty file in which you can create whatever m-file you want. What do I have to put on the First Line of a MATLAB function? The 1 st line of a function must contain the function definition, which has a general structure like this (see also the specific example below) 1 : function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m) where Out_1,Out_2,,Out_N are the N output variables and In_1,In_2,,In_M are the M input variables; If there is only a single output variable use: function Out_1 = function_name(in_1,in_2,,in_m) If there is no output variable use: function function_name(in_1,in_2,,in_m) What do I have to put after the 1 st line? After the first line, you just put a sequence of MATLAB commands with one command per line just like you are computing in MATLAB in the command line environment. This sequence of commands is what makes up your program you perform computations using the input variables and other variables you create within the function and in doing so, you create the output variables you desire. 1 Code in an m-file will be shown here using the Arial font, e.g., x = cos(0.1*pi*n)

2 How do I use the input variables in a MATLAB function? When you are writing the lines that make up your function you can use the names of the input variables defined in the first line just like they are previously created variables. So if In_1 is one of the input variables you could then do something like this: y=in_1.^2; This takes the values in In_1, squares them, and assigns the result to the variable y. Note: putting a semicolon at the end of an expression stops the display of the result a good idea unless you really WANT to see the result (sometimes useful when debugging or verifying a function). How do I make the output variables in a MATLAB function? On any line in your function you can assign any result you compute to any one of the output variables specified. For example: Out_1=cos(y); will compute the cosine of the values in the variable y and then assigns the result to the variable Out_1, which will then be output by the function (assuming that Out_1 was specified as an output variable name). How do I Save a MATLAB function? Once you have finished writing your function you have to save it as an m-file before you can use it. This is done in the same way you save a file in any other application: go to FILE, and SAVE. type in the name that you want to use o it is best to always use the function name as the file name o you don t need to explicitly specify the file type as *.m navigate to the folder where you want to save the function file o see below for more details on Where to Save an M-File? click on SAVE Where to Save an M-File? It doesn t really matter where you store it BUT when you want to use it, it needs to be somewhere in MATLAB s path or should be in MATLAB s present working directory (PWD) the path specifies all the folders where MATLAB will look for a function s file when the function is run the PWD specifies a single folder that MATLAB considers its primary folder for storing things it is generally advisable to specify an appropriate PWD each time you start up MATLAB and specify it to be wherever you have the m-files you are working on o Click on FILE, click on SET PATH, click on BROWSE, navigate to the folder you want as PWD and click on it, and then click OK

3 How do I Run an M-File? Once you have a function saved as an m-file with a name the same as the function name and in a folder that is either the PWD or is in MATLAB s path, you can run it from the command line: >> [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m) How do I Test an M-File? Once you have a file written you need to test it. When you try to run it the first time there is a good chance that it will have some syntax error that will cause its operation to terminate MATLAB will tell you on what line the operation was stopped, so you can focus immediately on somewhere further along in the function and will give you some idea if what the problem is. Just keep at it and you ll eventually get it to run, but here is a tip: open the m-file that you are debugging click on DEBUG on the toolbar at top click on STOP IF ERROR o note: there some other options that can be useful, so try them out Now when you run your function and it encounters an error, it will stop and will put you into a mode that will allow you to view all the variables at the point at which the error occurred o When you are stopped (i.e., in debug mode ) you have a different prompt than MATLAB s standard >> prompt o To quit from the debug mode click on DEBUG and the click on QUIT DEBUGGING When you are all done using this feature you can turn it off by clicking on DEBUG on the toolbar and then clicking on STOP IF ERROR (which should be checked to indicate that it was turned on) o Then you are returned to having the standard prompt Then, once you have it running without any syntax errors or warnings, you need to test it to verify that it really does what you intended it to do. Obviously, for simple functions you may be able to verify that it works by running a few examples and checking that the outputs are what you expect. Usually you need to do quite a few test cases to ensure that it is working correct. For more complex functions (or when you discover that the outputs don t match what you expect) you may want to check some of the intermediate results that you function computes to verify that they are working properly. To do this you set breakpoints that stop the operation of the function at a specified line and allow you then view from the command: open the m-file that you are debugging put the cursor in the line at which you want to set a breakpoint click on DEBUG on the toolbar at top and then click SET/CLEAR BREAKPOINT

4 Now when you run your function, it will stop at that line and will put you into a mode that will allow you to view all the variables at that point When you are stopped (i.e., in debug mode ) you have a different prompt than MATLAB s standard >> prompt o When you are all done using this feature you can turn it off by repeating the process used to set the breakpoint Once you have it stopped, any variable that has been computed up to that point can be inspected (plot it, look at its values, check its size, check if it is row or column, etc. You can even modify a variable s contents to correct a problem). Note that the ONLY variable you have access to are those that have been created inside the function or have been passed to it via the input arguments. Note that you can set multiple breakpoints at a time once you have stopped at the first one you can click on DEBUG and then click on CONTINUE and it will pick up execution immediately where it left off (but with the modified variables if you changed anything). Note also that once you have a function stopped in debug mode you can single-step through the next several lines: click on DEBUG and click on SINGLE STEP. Comments on Programming Style 1. In many ways, programming in MATLAB is a lot like programming in C, but there are some significant differences. Most notably, MATLAB can operate directly on vectors and matrices whereas in C you must operate directly on individual elements of an array. Because of this, loops are MUCH less common in MATLAB than they are in C: in C, if you want to add two vectors you have to loop over the elements in the vectors, adding an element to an element in each iteration of the loop; in MATLAB, you just issue a command to add the two vectors together and the vector addition of all the elements is done with this single command. 2. The comment symbol in MATLAB is. Anything that occurs after a on a line is considered to be comments. 3. It is often helpful to put several comment lines right after the function definition line. These comments explain what the function does, what the inputs and outputs are, and how to call the function. 4. Putting in lots of comments helps you and others understand what the function does from a grading point of view you will have a higher probability of getting full credit if you write comments that tell me what your code is doing An Example Here is an example of a MATLAB function. Suppose you would like to write a general routine that will compute the value of some arbitrary polynomial at an arbitrary set of equally-spaced x

5 values. This turns out to be something that is best done using loops (or at least, I couldn t find a clever way to avoid loops this is good because it at least gives an example of how to do loops). The function might look like this: function [y,x] = poly_equi(power,coeffs,xmin,xmax,del_x) USAGE: [y,x] = poly_equi(power,coeffs,xmin,xmax,del_x); Inputs: power = an integer specifying the highest power of the polynomial coeffs = a row vector of the polynomial's coefficients xmin = the desired minimum x value for evaluation xmax = the desired maximum x value for evaluation del_x = the desired spacing between the x values Output: x = a row vector of the x values y = a row vector of the y values Operation: if coeffs = [C_0 C_1 C_2... C_p], where p = power, this function computes In equation form, not in matlab syntax: y = C_0 + C_1x + C_2x^2 +... + C_px^p First, generate the x values as a row vector x = xmin:del_x:xmax; this uses MATLAB's colon operator to generate equally spaced points at a spacing of del_x for n=0:power Loop through the powers in the polynomial and compute a row vector for each of the terms in the polynomial and put that row vectro into each row of matrix X X(n+1,:)=coeffs(n+1)*x.^n; note use of "n+1" for indexing - matlab can't index using "0" end You now have a matrix X who's nth row is C_n*x.^n The x values run across this matrix, the power value runs down this matrix Now to create the values of y we have to add the rows together: if power>0 y=sum(x); when matlab's sum function is applied to a matrix it sums down the columns to give a row vector else y=x; if power=0 there is only a single row in X, so no need to sum end Now, to run this function we could do this:» [y_0,x_0] = poly_equi(0,3,-5.1,5.0,0.2);» [y_1,x_1] = poly_equi(1,[3 2],-5.1,5.0,0.2);» [y_2,x_2] = poly_equi(2,[3 2 2],-5.1,5.0,0.2);» subplot(3,1,1)» plot(x_0,y_0)» xlabel('x values')

6» ylabel('y values')» subplot(3,1,2)» plot(x_1,y_1)» xlabel('x values')» ylabel('y values')» subplot(3,1,3)» plot(x_2,y_2)» xlabel('x values')» ylabel('y values') Note that we ran the function three times each time we put in different values for the input variables and called the output variables something different each time so that we could store the three different results. We then plotted the results on three different subplots and labeled the axes. And label the UNITS of the values if it makes sense!!!!!!