MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

Slides:



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

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
MATLAB Optimization Greg Reese, Ph.D Research Computing Support Group Miami University.
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.
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:
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
Scripts and Flow Control. Scripts So far we have been entering commands directly into the command line But there is a better way Script files (and functions)
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
MATLAB Cell Arrays Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
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.
Lecture 1: Introduction Lecture series based on the text: Essential MATLAB for Engineers and Scientists By Hahn & Valentine
BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.
Introduction to Shell Script Programming
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.
Microsoft Excel 2007 © Wiley Publishing All Rights Reserved. The L Line The Express Line to Learning L Line.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 4.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
GUI development with Matlab: GUI Front Panel Components 1 GUI front panel components In this section, we will look at -GUI front panel components -Programming.
MATLAB An Introduction to MATLAB (Matrix Laboratory) 1.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 1.
Copyright © The McGraw-Hill Companies, Inc. Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 1 An Overview of MATLAB.
Numerical Computation Lecture 2: Introduction to Matlab Programming United International College.
Chapter 1: Getting Started with MATLAB MATLAB for Scientist and Engineers Using Symbolic Toolbox.
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
A Brief introduction to MatLAB ($50 - $99 for students)
1 C++ Programming Basics Chapter 2 Lecture CSIS 10A.
CMPS 1371 Introduction to Computing for Engineers MatLab.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
Script M-Files Group of Matlab commands placed in a text file with a text editor. Matlab can open and execute the commands exactly as if they were entered.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Scientific Computing Introduction to Matlab Programming.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
1 Week 1: Variables, assignment, expressions READING: 1.2 – 1.4.
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.
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.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Files Tutor: You will need ….
Introduction to MATLAB Section2, statistics course Third year biomedical dept. Dina El Kholy, Ahmed Dalal.
MA/CS 375 Fall 2003 Lecture 3. .* Multiplication We can use the.* operator to perform multiplication entry by entry of two matrices:
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
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.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
 Prepared by: Eng. Maryam Adel Abdel-Hady
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Release Numbers MATLAB is updated regularly
Matlab Training Session 4: Control, Flow and Functions
Introduction to MATLAB for Engineers, Third Edition
Variables, Expressions, and IO
Basic operations in Matlab
Lecture 1: Introduction
Functions In Matlab.
Experiment No. (1) - an introduction to MATLAB
Unit 3: Variables in Java
Presentation transcript:

MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013

MATLAB Functions – Part I © Greg Reese. All rights reserved 2

3 M-files M-file Text file that holds MATLAB commands or code File ends in.m (for MATLAB) Can hold a script or a function Portable across platforms

Scripts 4

5 A script is a sequence of MATLAB commands stored in an m-file Type in file as you would enter on command line –Don't type prompt ( >> ) Scripts are simplest m-files because they have no input or output passed to or from them

6 Scripts To call a script is to execute (run) the commands in the script file Call a script by typing its file's name (the.m is optional) A script can be called from: The MATLAB command line Another script A function (to be discussed later)

7 Scripts When you run a script from the command line All variables created in the script remain in your workspace The script can access all variables that were in the workspace before it ran

8 Scripts Script a = 3; c = 9; BEFORE a = 7 b = 5 No other variables AFTER a = 3 b = 5 c = 9 Note: a changed b unchanged c added

9 Scripts Running a script can change the value of variables you have stored, or even erase the variables!

10 Scripts Scripts useful for: Automating series of MATLAB commands, e.g., ones you have to perform repeatedly from the command line Initializing workspace

11 Scripts Try It – automating commands 1.Remove all variables in your workspace by typing clear all and confirm by typing whos 2.Download the script petals.m and run it 3.Type whos to see if there are any variables >> whos Name Size Bytes Class Attributes k 1x1 8 double rho 4x double theta 1x double

12 Scripts MATLAB runs startup.m when it starts. Put commands in file to set up your environment Set working directory Store often-used variables Add directory of group functions to MATLAB path

13 Scripts Try It – initialize environment 1.Type edit startup –Add the three lines cd some_directory hbar = e-27 / ( 2*pi); mileToKm = 1.6; 2.At the command line type startup 3.Verify that you're in the right directory and the two variables are set Put in name of directory on your machine

14 Scripts Questions?

Using MATLAB Functions 15

16 Functions You’re likely to want to compute functions of a variable, e.g., MATLAB has a large number of standard mathematical functions. To compute the function of a variable write the function name followed by the variable in parentheses.

17 Functions Example exp(x) sqrt(x) Usually store result in a variable, e.g., root_x=sqrt(x) Can pass constants too, e.g., root_2=sqrt(2)

18 Functions You can make complicated expressions by combining variables, functions, and arithmetic, e.g., 5*exp(-k*t)+17.4*sin(2*pi*t/T) Note how similar math and MATLAB are. Math MATLAB “ * ” means “×”

19 Functions Try It Compute these The sine of 90° is 1. Use the MATLAB function sin to compute the sine of 90°. Waz up?

20 Functions The MATLAB function sin is not doing what we expect. To get more information on a MATLAB function function_name, type >> help function_name (Don’t include any parentheses.) Try It Find out more about sin

21 Getting help The help information explains that the argument is in radians, not degrees.

22 Getting help The help information often has links to related functions. Type help sin again and click on the link sind. It tells you that sind computes the sine of an argument that is in degrees.

23 Getting help What if you don’t know the MATLAB name of a mathematical function? Use >> lookfor word to search in the basic help information for “word”.

24 Getting help Example – what MATLAB function computes the inverse tangent? >> lookfor tangent produces 13 results of which three also say inverse – ATAN, ATAN2, and ATAND

25 Getting help Questions?

Writing Functions 26

27 Writing Functions A function is a MATLAB program that can accept inputs and produce outputs. Some functions don't take any inputs and/or produce outputs. A function is called or executed (run) by another program or function. That program can pass it input and receive the function's output.

28 Writing Functions Why use functions? Use same code in more than one place in program Reuse code by calling in different programs Make debugging easier by putting all of one kind of functionality in one place

29 Writing Functions Think of a function as a black box. Calling program can't see (access) any of the variables inside the function Function can't see any variables in the calling program Function a = 5 b = ? InputOutput Calling Program a = ? b = 9

30 Writing Functions The code for a function is in an m-file. You can make the file in any text editor but it's easiest to do it with the MATLAB editor. To do this, at the command prompt type edit followed optionally by a filename not in quotes if file in current directory, MATLAB opens it if not in current directory, MATLAB creates it

31 Writing Functions What path does the baseball take? How far does it go? What's the best angle to throw it at?

32 Writing Functions y(t) = v sinθ t – ½ gt 2 v is initial speed (velocity) g is 32 feet/sec 2 t is time θ is throw angle t y(t ) Time Height θ V

33 Writing Functions As soon as you make an m-file, give it a name (if needed) and save it. Do this by choosing “Save” or “Save as” under the file menu. Try It Make an m-file to compute the baseball height at a given time and call the file height.m >> edit height.m Choose File menu, Save

34 Writing Functions Function names Must begin with a letter Can contain any letters, numbers, or an underscore Name of file that contains function should be function name with “.m” appended –Example: the function compute_area should be in the file called compute_area.m

35 Writing Functions function y = fname( v1, v2 ) First line of function is called the function line “function” – keyword that tells MATLAB function starts with this line. Must be the word “function” “y” – output variable(s). Can be any variable name “fname” – any function name “v1”, “v2” – input variable(s). Can be any variable name

36 Writing Functions function y = fname( v1, v2 ) Function ends when: 1.Another function line appears 2.An end-statement that matches the function line appears 3.There's no more code in file If function has outputs, must declare variables with output variable names and compute their values before function ends

37 Writing Functions Try It Make the first line of your function be function h = height( time )

38 Writing Functions Pitcher #1 Greg (G-Dog) Reese Fastball = 40 mph * = 44 feet/sec * with strong tailwind

function h = height( time ) g = 32; speed = 44; angle = 70; h = ? 39 Writing Functions Try It Write a function called height that accepts a time as an argument and returns the height at that time. Use the MATLAB function sind() to calculate the sine of an angle in degrees y(t) = v sinθ t – ½ gt 2 function h = height( time ) g = 32; speed = 44; angle = 70; h = speed*sind(angle)*time - 0.5*g*time^2; Can be any name, but must be same name

40 Writing Functions To make the code clearer you can write comments, text that MATLAB ignores. If MATLAB sees a percent sign (%) it ignores the sign and everything after it on the rest of the line function h = height( time ) g = 32; % feet/sec^2 speed = 44; % feet/sec angle = 70; % degrees h = speed*sind(angle)*time - 0.5*g*time^2;

41 Writing Functions CAREFUL! You MUST save the file for any changes you made to go into effect. If you've fixed an error but your function still doesn't seem to work, make sure you saved the file. TIP If all changes to a file have been saved, the “save-icon”, a diskette, will be disabled (grayed-out) Grayed-out “save” icon

42 Writing Functions To call a function type its name followed by the arguments in parentheses. If no arguments, can omit parentheses Try It >> height(1) ans = >> height(2.5) ans =

43 Writing Functions Often save result in a variable Try It >> h1 = height(1) h1 = >> h2 = height(2) h2 = >> h1 h1 =

44 Writing Functions Many functions require other functions to be passed to them. For example: quad() – integration fminbnd() – finding minimum ezplot() – quick plot of function

45 Writing Functions To pass one function to another, use a function handle Function handle –MATLAB data type that contains all info needed to evaluate function –Make a function handle by putting character in front of the function name

46 Writing Functions Can see your function over range of values by using MATLAB function ezplot() To use: [ t1 t2 ] ) Must myFunction can have any name but must accept one and only one argument t1 and t2 are starting and ending plotted values of argument ez=easy

47 Writing Functions Try It Plot the baseball's height from when it's thrown to 2½ seconds later >> [0 2.5] ) Ignore the message Warning: Function failed to evaluate on array inputs;

48 Writing Functions Distance d that ball travels is d = v 2 sin(2θ) / g v is initial speed (velocity) g is 32 feet/sec 2 θ is throw angle x Distance θ V

function distance = distance( speed ) g = 32; % feet/sec^2 angle = 70; % degrees distance = ?; function distance = distance( speed ) g = 32; % feet/sec^2 angle = 70; % degrees distance = speed^2 * sind(2*angle) / g; 49 Writing Functions Try It Write a function called distance that accepts a speed as an argument and returns the distance the ball was thrown. d = v 2 sin(2θ) / g

>> speed1 = 44; >> distance( speed1 ) ans = Writing Functions Try It Store pitcher 1's speed (44 ft/sec) in a variable and find out how far he threw the ball

51 Writing Functions Pitcher #2 Nolan (The Ryan Express) Ryan Fastball = over 100 mph * = 147 feet/sec * even after he turned 40!

>> speed2 = 147; >> distance( speed2 ) ans = Writing Functions Try It Store pitcher 2's speed (147 ft/sec) in a variable and find out how far he threw the ball

53 Writing Functions Try It Make a graph of how the distance the ball flies depends on the speed at which it's thrown. Plot the results from 40 to 140 feet/sec >> [40 140] )

function distance = distance2( speed, angle ) g = 32; % feet/sec^2 distance = speed^2 * sind(2*angle) / g; 54 Writing Functions Try It The distance depends on both the velocity and the angle. Write a function called distance2 that takes both those arguments and computes the distance d = v 2 sin(2θ)/g

>> distance2(speed1,20) ans = >> distance2(speed2,20) ans = >> distance2(speed1,50) ans = >> distance2(speed2,50) ans = Writing Functions Try It d = v 2 sin(2θ) / g Compute how far both pitchers throw the ball at a 20 o angle and at a 50 o angle

56 Writing Functions Want to find "best" angle, i.e., angle that makes the ball go the farthest. One way to do this is to plot distance2( speed, angle) over the range of angles from 0 o to 90 o Problem: ezplot requires that the function passed to it have exactly one argument, but distance2 has two arguments

57 Writing Functions One solution – write another function that accepts only the angle and has the speed stored in it. This function calls distance2 function distance = distance1( angle ) speed = 44; distance = distance2( speed, angle ); >> [0 90] )

58 Writing Functions Drawbacks Have to make another m-file When speed changes, have to edit the m-file

59 Writing Functions Better solution Use an anonymous function to convert distance2 to a function that accepts only one argument

60 Writing Functions Anonymous function – a quick way to write a simple function without having to make an expression arguments – list of arguments separated by commas expression – a single MATLAB expression. Can be a call of another function!

Try It 61 Writing Functions >> 90] ) anonymous function expression "frozen" varies

62 Writing Functions >> 90] )

63 Writing Functions Try It What angle should pitcher 1 throw the ball at to make it go as far as possible? 45 o

64 Writing Functions Try It Repeat for pitcher2 45 o

65 Writing Functions Can plot more than one data set on a graph. To do so: 1.Type the hold on command 2.Type the various ezplot calls 3.Type the hold off command

66 Writing Functions Try It Draw the angle-distance plots for both pitchers on the same graph >> hold on >> 90] ) >> 90] ) >> hold off

67 Writing Functions In other words… For the greatest distance throw the ball at a 45 o angle, regardless of how strong your arm is!

68 Writing Functions What angle should you throw the ball at to make it go as far as possible? Another solution – use a MATLAB optimization function to find the angle that maximizes the distance

69 Writing Functions fminbnd finds the minimum of a single- variable function on a specified interval >> x = x1, x2 ) fun is a function that has exactly one argument x1 and x2 are the starting and ending points of the interval

70 Writing Functions Tip fminbnd finds the minimum of a function fun(x). To find the maximum, use the negative of the function, i.e., -fun(x)

71 Writing Functions Try It Use fminbnd to find the best angle for both pitchers >> -distance2(speed1,angle),0,90 ) ans = 45 >> -distance2(speed2,angle),0,90 ) ans =45

72 Writing Functions Questions?

73 The End