ENG 1181 1 College of Engineering Engineering Education Innovation Center 1 Functions 1 in MATLAB Topics Covered: 1.Uses of Functions Organizational Tool.

Slides:



Advertisements
Similar presentations
Lecture 14 User-defined functions Function: concept, syntax, and examples © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Advertisements

Lecture 5.
Functions in MatLab Create a new folder on your Z:drive called MatLab_Class24 Start MatLab and change your current directory to MatLab_Class24 Topics:
The Web Warrior Guide to Web Design Technologies
Flow Charts, Loop Structures
Introduction to Engineering MATLAB - 12 Agenda Function files.
Example 2.
Chapter 20 Thinking Big: Functions. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Anatomy of a Function Functions are packages for.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
Programming in Matlab Day 1: Basics. Matlab as a calculator >> 2+2 ans = 4 >> 2^3 ans = 8 >> sqrt(2) ans = Command Window Basic operations Sum:
Chapter 4 Sec. 4.1, 4.2, 4.4 Procedures (User-defined)
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.
Fortran- Subprograms Chapters 6, 7 in your Fortran book.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Functions 1 parameter, 2 return-values "Conversion of time format" One problem. 5 steps to solve it. 1.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #002 (January 17, 2015)
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
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.
ENG 1181 College of Engineering Engineering Education Innovation Center MATLAB is a powerful program for numerical computations, plotting and programming.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
Copyright © The McGraw-Hill Companies, Inc. Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 1 An Overview of MATLAB.
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.
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.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
CMPS 1371 Introduction to Computing for Engineers MatLab.
Definition CSS “Short for Cascading Style Sheets, a new feature being added to HTML that gives both Web site developers and users more control over how.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Getting Started with MATLAB (part2) 1. Basic Data manipulation 2. Basic Data Understanding 1. The Binary System 2. The ASCII Table 3. Creating Good Variables.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
ENG College of Engineering Engineering Education Innovation Center 1 More Script Files in MATLAB Script File I/O : Chapter 4 1.Global Variables.
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.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
ENG College of Engineering Engineering Education Innovation Center 1 MATLAB – Functions 1 Topics Covered: 1.Functions 2.Function files Functions.
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.
ENG College of Engineering Engineering Education Innovation Center 1 Basic For Loops in MATLAB Programming in MATLAB / Chapter 6 Topics Covered:
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
JavaScript 1 COE 201- Computer Proficiency. Introduction JavaScript scripting language ▫Originally created by Netscape ▫Facilitates disciplined approach.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Recap Functions with No input OR No output Determining The Number of Input and Output Arguments Local Variables Global Variables Creating ToolBox of Functions.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
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.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
ENG College of Engineering Engineering Education Innovation Center 1 Functions 2 in MATLAB Topics Covered: 1.Functions in Script Files Inline Functions.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
User Defined Functions
T. Jumana Abu Shmais – AOU - Riyadh
Functions In Matlab.
funCTIONs and Data Import/Export
Note on Indexing of Array Elements
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Experiment No. (1) - an introduction to MATLAB
Using Script Files and Managing Data
Scripts In Matlab.
Matlab Basics Tutorial
Executive Reports, Instructions and Documentation
Presentation transcript:

ENG College of Engineering Engineering Education Innovation Center 1 Functions 1 in MATLAB Topics Covered: 1.Uses of Functions Organizational Tool User Function Library 2.Function Syntax User Defined Functions / Chapter 6

ENG Why Not Use Script Files For Everything? Imagine that you’re heading a programming group supervising 10 programmers. Imagine that you have to allocate tasks to create a new application program. Imagine that everything is done with script files. What would you have to do? Create a table of all variable names to be used in every part of the program

ENG Why Not Use Script Files For Everything? Imagine you created a useful set of code two years ago and would like to use it again for a new program Wouldn’t it be nice to not have to remember exactly what you did? If back then you used a variable name you’d like to use for something else now – wouldn’t it be nice to not have to find all cases and change it?

ENG Consider the built in functions like the sin(x) function Do you have to know every variable name used by the person who programmed it? Wouldn’t it be nice to do the same with your own programming? Function files help solve these problems. Why Not Use Script Files For Everything?

ENG Function Files Every programming language has a way to do this. In MATLAB it’s called a user-defined function In FORTRAN and BASIC it’s called a subroutine In PASCAL it’s called a procedure In C it’s also called a function

ENG A USER-DEFINED FUNCTION IN A FUNCTION FILE Function File Input dataOutput  A user-defined function is a program created by the user and can be used like a built-in function.  Its main feature is that it has an input and an output.  The function can be used many times with different values of the input data.

ENG FUNCTION FILE A function file is a program that can be used in two ways:  Perform tasks that are used frequently  Be a subprogram in a large program In this way a large program can be made of smaller “building blocks” that can be developed independently

ENG Programming Insight In practice, only the top level of a program is a script file. The script file interacts with the user and keeps track of calling the other routines (like a project manager). ALL other routines are functions. Because of this, function files never use the input command

ENG Programming Insight User created function files can either be in the current working directory or be placed into a user library whose location has been added to MATLAB’s search path. Add a folder to MATLAB’s search path by going to File > Set Path Click on the “Add a Folder” button and indicate the folder you want to add Don’t forget to “Save” if you want this folder used in future MATLAB sessions!

ENG FUNCTION FILE  Once they are created, the functions can be used in the Command Window, in script files, or inside other function files  Data is transferred to a function file by input variables and the results are transferred back by output variables.  All variables inside the function are local (NOT global), (they are not recognized by other parts of MATLAB – e.g. the command window or any script file)

ENG FUNCTION FILE  User-defined Function files are used in the same way as built-in functions, (i.e. once they are created, functions can be used in the Command Window, in script files, in equations, or inside other function files)  Data is transferred to a function file by input variables and the results are transferred back by output variables.  All the calculations and the variables that are used inside the function are local, (i.e. they are not recognized by, transferred to, or available to other parts of MATLAB)

ENG CREATING A FUNCTION FILE A function file is created in the Editor/Debugger Window (the same window that is used to create script files). 142 The first line of the function file is typed here. It must be the function definition line.

ENG STRUCTURE OF A FUNCTION FILE 143 function [mPay, tPay] = loan(amount, rate, years) % loan() calculates monthly and total payment of loan % Input arguments: % amount = loan amount in $ % rate = annual interest rate in percent % years = number of years % Output arguments: % mPay = monthly payment % tPay = total payment ratePerMonth = rate * 0.01 / 12; rPM = (1 + ratePerMonth) ^ (years * 12); mPay = amount * rPM * ratePerMonth / (rPM - 1); tPay = mPay * years * 12; Function definition line Help text Function body (Program) Assign values to output arguments Output arguments Input arguments

ENG FUNCTION DEFINITION LINE The function definition line: 1.Defines that the M-file is a function 2.Defines the name of the function 3.Lists the input and output variables function [output vars] = function_name(input vars) function [mpay, tpay] = loan(amount, rate, years) The first line of a function file MUST be the function definition line (without this line it will be a script file) Example:

ENG THE FUNCTION DEFINITION LINE  The word function must be typed in lower case letters (if it is wrong, it won’t turn blue)  Square brackets are not required in the function definition line if the function has only one output variable: function [A] = RectArea(a,b) function A = RectArea(a,b)  If there are no output variables, the square brackets and the equal sign can be omitted: function CirclePlot(r) Either form is ok

ENG  The names of the input and output variables given in the function definition line and in the body of the function are local.  The variables are assigned according to their position in the output or input variables list in the function definition line.  Do not name a function file a name that is already used by MATLAB for a built-in function. To check if a function name is used by MATLAB type “help name” in the Command Window THE FUNCTION DEFINITION LINE

ENG FUNCTION EXAMPLE w = 5; h = 10; a = RectArea(w, h);... Memory (main) w h a 5 function area = RectArea(width, height) area = width * height; Memory (local function) width height area Call a function to calculate the area of a rectangle with sides w and h. Script file

ENG SAVING A FUNCTION FILE (similar to saving a script file)  Once the script file is completed, it must be saved. In our class use Save As and save: (N:\, USB drive). Save it in the working directory.  The file MUST be saved with a name that is identical to the function name in the function definition line  “Save and Run” will not work, since the function needs to be called from somewhere with input values.  It is common to forget to save changes, in which case MATLAB will run the OLD version. 147

ENG EXAMPLES OF FUNCTION DEFINITION LINES 145 Three input variables, two output variables, save as loan.m Two input variables, one output variable, save as RectArea.m One input variable, two output variables, save as SphereVolArea.m Three input variables, no output variables, save as trajectory.m function [mpay, tpay] = loan(amount, rate, years) function trajectory(velocity, height, gravity) function [volume, surfArea] = SphereVolArea(radius) function [area] = RectArea(width, height)

ENG USING A USER-DEFINED-FUNCTION (FUNCTION FILE)  A user-defined function is used in the same way as a built-in function.  To use a function file, the directory where it was saved must either be in the current directory, or be in the search path (same as required for a script file).  A variable that is assigned a value in the code of the function file will be displayed in the Command Window, unless a semicolon is typed at the end of the command (always use semicolons in functions) 148

ENG EXAMPLE OF A FUNCTION FILE 143 function [mPay, tPay] = loan(amount, rate, years) % loan() calculates monthly and total payment of loan % Input arguments: % amount = loan amount in $ % rate = annual interest rate in percent % years = number of years % Output arguments: % mPay = monthly payment % tPay = total payment ratePerMonth = rate * 0.01 / 12; rPM = (1 + ratePerMonth) ^ (years * 12); mPay = amount * rPM * ratePerMonth / (rPM - 1); tPay = mPay * years * 12; Function definition line Help text Function body (Program) Assign values to output arguments Input arguments Output arguments

ENG >> [month total] = loan(25000, 7.5, 4) month = total = >> a = 70000; b = 6.5; >> [x y] = loan(a, b, 30) x = y = EXECUTING THE loan() FUNCTION 148 First input argument is loan amount Second is interest rate Third is the number of years Define variables a and b. Use a, b, and the number 30 for input arguments and x (monthly pay) and y (total pay) for output arguments.