Advanced use of functions Anonymous functions function handles subfunctions and nested functions.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

MATLAB Tutorial ECE 002 Professor S. Ahmadi.
PHP Reusing Code and Writing Functions.
Lecture 5.
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.
Modular Programming With Functions
M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even.
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
MATLAB Functions – Part II Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.
More on Functions… Lecture 8. Preserving Data between Calls to a function Persistent statement is declared in order to preserve some local information.
COS 381 Day 19. Agenda  Assignment 5 Posted Due April 7  Exam 3 which was originally scheduled for Apr 4 is going to on April 13 XML & Perl (Chap 8-10)
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Introduction to Computers and Programming Strings Professor: Evan Korth New York University.
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
Dr. Jie Zou PHY Welcome to PHY 3320 Computational Methods in Physics and Engineering.
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
Lecture 24 Introduction to state variable modeling Overall idea Example Simulating system response using MATLAB Related educational modules: –Section 2.6.1,
Builtin and user defined functions
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.
MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
C++ for Engineers and Scientists Third Edition
Computer Science Standard Level Mastery Aspects. Mastery Item Claimed JustificationWhere Listed Arrays Used to store the student data Lines P.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Matlab Programming for Engineers Dr. Nidal Farhat Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
Function M-File Numerical Computing with. MATLAB for Scientists and Engineers.
Recap Function M-files Syntax of Function M-Files Comments Multiple Input and Output Functions.
Introduction to Engineering MATLAB – 2 Introduction to MATLAB - 2 Agenda Defining Variables MATLAB Windows.
1 Programming in C Hello World! Soon I will control the world! Soon I will control the world!
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Introduction to Matlab Patrice Koehl Department of Biological Sciences National University of Singapore
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
ENG College of Engineering Engineering Education Innovation Center 1 Functions 2 in MATLAB Topics Covered: 1.Functions in Script Files Inline Functions.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Lecture 2 Functions Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University of Washington.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Introduction to Matlab
Introduction to Programming for Mechanical Engineers
Other Kinds of Arrays Chapter 11
Lecture 2 Introduction to Programming
User Defined Functions
C++ for Engineers and Scientists Second Edition
CHAPTER FOUR Functions.
Functions In Matlab.
Iteration: Beyond the Basic PERFORM
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
The Three Attributes of an Identifier
Presentation transcript:

Advanced use of functions Anonymous functions function handles subfunctions and nested functions

Function handle Useful as a parameter to other functions Can be considered as an alternate name for a function – but with more capabilities Example: sine_handle sine_handle(x) has same values as sin(x) for all x

Three ways of plotting sin(x) x = [0 : 0.01 : 2*pi] ; y = sin( x ); plot(x,y) plot( x, sin(x) ) plot( [0 : 0.01 : 2*pi], sin( [0 : 0.01 : 2*pi] )) ; Last method has the advantage that no permanent storage is needed for x and/or y

Function handle continued In last example everything is on one line but it requires writing the interval twice It would be more convient to write gen_plot( function_handle, interval ) The first parameter has to be a function handle and not just the name of a function gen_plot( sin, [0 : 0.01 : 2*pi ] ) does not make sense to Matlab, but the following does gen_plot( sine_handle, [0 : 0.01 : 2*pi] )

Using a function handle When plotting lots of functions it may be useful to have a function with the name gen_plot available function [] = gen_plot( func_handle, interval ) ; plot( interval, func_handle(interval) ) ; The example shows how to pass functions as parameters. gen_plot( sine_handle, [0 : 0.01 : 2*pi] )

Anonymous functions Assume the user needs to work temporarily with the function x 3 +3*x – 1 Instead of writing the function function y = mypoly(x) ; y = x.^3+3*x-1 and storing it as mypoly.m in subdirectory work we can use an anonymous function with the function handle mypoly mypoly x.^3+3*x-1

Using anonymous functions With a function handle an anonymous function can be used like any other gen_plot( mypoly, [-10 : 0.01 : 10] ) or try to find a zero near 1.5 fzero( mypoly, 1.5 ) Without the function handle the anonymous function can also be inserted directly as a parameter x.^3+3*x-1, [-10 : 0.01 : 10] )

More examples f1 x + 2* exp(-x) -3 fzero( f1, 0 ) fzero( f1, 1 ) Assume f1 had been defined as a function and kept in f1.m then fzero( f1, 0 ) would be in error Matlab used an alternate method in the past. In order to be backward compatible it is still available, but the use is not recommended: fzero( 'f1', 0 ) fzero( 'sin', 0 ) fzero( 'x.^3', 0 ) need to use default variable name x Use function handles instead!

Commands of Matlab: clear, dir, which, cd, … they can be used with a parameter, i.e. clear functions dir C:\MATLAB_SV701\toolbox\matlab which clear cd E:\work all are builtin functions the parameter is interpreted as a character string. A blank terminates the character string equivalent calls clear('functions') dir('C:\MATLAB_SV701\toolbox\matlab') which('clear') cd(' e:\work')

Remark: Builtin functions can be called like a command median [1,2,100] instead of median([1,2,100]) Matlab gives no warning in the first case and returns 1 [1,2,100] is treated as a character string median('[1,2,100]') also returns 1

Subfunctions, example function [avg,med] = mystat(u) n = length(u) ; avg = mymean( u,n ) ; med = mymedian( u,n ) ; end % function mystat function a = mymean( v,n ) a = sum(v)/n; end % function mymean function m = mymedian( v,n ) ; w = sort(v) ; if rem(n,2) ==1 m = w((n+1)/2) else m = (w(n/2)+ w(n/2+1))/2 ; end end % mymedian

Subfunctions subfunctions are stored in the same file as the main function and can only be called in that file the scope of subfunctions is restricted to the file in which they are defined the example given is for illustration only the example uses modular design, but carries it to an extreme the overhead of calling a function outweighs any benefit in this case if a function mystat has to be written the following would be acceptable

Avoid unnecessary calculations function [avg,med] = mystat2(u) n = length(u) ; avg = sum(u)/n ; if nargout == 2 % only compute if requested w = sort(u) ; if rem(n,2) ==1 med = w((n+1)/2) ; else med = (w(n/2)+ w(n/2+1))/2 ; end end % mystat2

Nested functions main_function nested_function_1 … end % nested_function_1 nested_function_2 … end % nested_function_2 … end % main_function

Nested function When using nested functions all functions need a matching end statement! subfunction versus nested functions nested functions have access to all variables defined in the main function! avoids passing parameters or using global variables For a structured design use subfunctions. Avoid nested functions or use them sparingly