COMP 116: Introduction to Scientific Programming Lecture 11: Functions.

Slides:



Advertisements
Similar presentations
Functions M-file with the function keyword. First line: –[myout1, myout2,..] = myfunction(a, b,…) Function called by name of m-file, not function name,
Advertisements

Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Lecture 14 User-defined functions Function: concept, syntax, and examples © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Lecture 5.
COMP 116: Introduction to Scientific Programming Lecture 37: Final Review.
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.
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.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Functions.
VBA Modules, Functions, Variables, and Constants
Functions MATLAB’s power comes from functions Functions allow projects to be partitioned into manageable, testable, reusable modules.
EGR 106 – Week 8 Data Files & Functions Interacting with Data Files Functions – Concept – Examples and applications Textbook chapter ,
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
Guide To UNIX Using Linux Third Edition
MATLAB and Simulinklecture 31 To days Outline  Functions  Strings  Sparse Arrays  Cell Arrays  Structures  Exercises on this days topics.
Introduction to Methods
Functions UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
CS190/295 Programming in Python for Life Sciences: Lecture 1 Instructor: Xiaohui Xie University of California, Irvine.
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.
Lecture 1: Introduction Lecture series based on the text: Essential MATLAB for Engineers and Scientists By Hahn & Valentine
Functions 1 parameter, 2 return-values "Conversion of time format" One problem. 5 steps to solve it. 1.
PYTHON. Python is a high-level, interpreted, interactive and object- oriented scripting language. Python was designed to be highly readable which uses.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Matlab Programming for Engineers Dr. Nidal Farhat Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.
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.
Function M-File Numerical Computing with. MATLAB for Scientists and Engineers.
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 6”
Functions CS 103 March 3, Review A function is a set of code we can execute on command to perform a specific task A function is a set of code we.
Functions CS 103. Review A function is a set of code we can execute on command to perform a specific task When we call a function, we can pass arguments.
Digital Image Processing Lecture10: MATLAB Example – Utility M-functions for Intensity Transformations.
CMPS 1371 Introduction to Computing for Engineers MatLab.
COMP An Introduction to Computer Programming : University of the West Indies COMP6015 An Introduction to Computer Programming Lecture 05.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
CPS120: Introduction to Computer Science Lecture 14 Functions.
EGR 106 – Functions Functions – Concept – Examples and applications Textbook chapter p15-165, 6.11(p 178)
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.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
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.
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.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
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.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Introduction to simple functions.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
The single most important skill for a computer programmer is problem solving Problem solving means the ability to formulate problems, think creatively.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 9: Value-Returning Functions
User-Written Functions
Learning to Program D is for Digital.
Introduction To Repetition The for loop
Matlab Training Session 4: Control, Flow and Functions
CS 326 Programming Languages, Concepts and Implementation
Functions CIS 40 – Introduction to Programming in Python
Scripts & Functions Scripts and functions are contained in .m-files
CS190/295 Programming in Python for Life Sciences: Lecture 1
Functions In Matlab.
Introduction to Computer Science
Presentation transcript:

COMP 116: Introduction to Scientific Programming Lecture 11: Functions

So far Script files ◦ All code inside one big file ◦ Perhaps structured into cells Used built-in matlab functions ◦ sin, cos, zeros etc. How do we structure more complex code? How do we write our own functions?

Calling Functions How does MATLAB call its own functions? Matlab loads it’s own function files and runs them through the interpreter ◦ Input variables map onto function inputs ◦ Function outputs get stored in specified variables % MyScript.m x = [ ]; maxX = max(x);... % MyScript.m x = [ ]; maxX = max(x);... max.m input output

Calling Functions How does MATLAB call its own functions? In MATLAB, each function should go into a separate m-file % MyScript.m x = [ ]; maxX = max(x);... % MyScript.m x = [ ]; maxX = max(x);... max.m input output

Syntax vs. Semantics What is syntax? ◦ Grammar ◦ Rules that let you write in the language ◦ Punctuation, etc. Why do we need syntax rules? ◦ Syntax rules allow compilers and interpreters to correctly convert our source code into something the computer understands.

Semantics What are semantics? ◦ Meaning ◦ What does your function actually do? ◦ What problem(s) does it solve?

Writing a function: Syntax function [outputs] = funcName( inputs ) % Function Comments … % Body (implementation) end %optional Note: The name of the function and the name of the m-file should be the same

Function Syntax Must start with function keyword ◦ Otherwise, it’s a script

Function Syntax Function name ◦ Again: remember that this must be the same as the name of the m-file

Function Syntax Function return values/output ◦ Potentially multiple values may be returned from the function ◦[r, c] = size(A)

Function Syntax Function input values/parameters ◦ Potentially multiple arguments may be passed into a function ◦s = sum(A, 2)

Function Syntax Comment block, just below the first line ◦ Searched by lookfor ◦ Displayed when you type help

Function implementation ◦ Where you do all the ‘work’ ◦ Has comments, expression, function calls… Function Syntax

Jargon Parameters ◦ The variables declared in the function interface Arguments ◦ The actual values supplied when the function is called. These are function parameters When calling the function: c = DiceToss(num_throws, desired_value); These are function arguments

A summary of function rules Most important: function name and its corresponding.m file name should match. Functions can have several inputs ◦ common in most languages Functions can also have several outputs ◦ This is different from most other languages. Input and output are optional Comments are optional ◦ But a good programming practice

More rules … One function per file ◦ Exception: helper functions  Meant to only be used internally by the main function function [avg, med] = newstats(u) % NEWSTATS Find mean w/ subfuctions. n = length(u); avg = helper_mean(u, n); function a = helper_mean(v, n) % Subfunction: calculate average. a = sum(v)/n; All in a single m file

More rules … Function Names are case sensitive ◦DiceToss is different from dicetoss is different from diceToss …

More rules … function [avg, med] = newstats(u) % NEWSTATS Find mean w/ subfuctions. n = length(u); avg = helper_mean(u, n); function a = helper_mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

More rules … Gotcha: you can accidently hide system functions, constants, and workspace variables by creating your own function with the exact same name. function [avg, med] = newstats(u) % NEWSTATS Find mean w/ subfuctions. n = length(u); avg = mean(u, n); function a = mean(v, n) % Subfunction: calculate average. a = sum(v)/n;

More rules … Be careful with parentheses: [] vs () ◦[r, c] = size(A) ◦(r, c) = size(A) ◦[r, c] = size[A] Think: ◦ Difference between  myfunc([1, 2, 3]) and myfunc(1, 2, 3) Incorrect

Function examples Multiple inputs No inputs Multiple outputs No outputs

Exercise 1 Write an absolute value function ◦ Assume the input is just a scalar Convert your guess-the-number script to a function ◦ What is the input? ◦ What is the output?

Scope Functions run in their own ‘workspaces’ MATLAB sq.m x =4 x2 =16 foo =4 x2 =5 bar =16

Scope: G lobal Variables (Workspace) Global MATLAB workspace ◦ Variables belonging to script files and command window Workspace Variables ◦ come into existence after they are created by assignment. ◦ exist until MATLAB quits or clear command is used on variables to remove them. ◦ Accessible from command window and scripts ◦ NOT accessible from inside functions

Scope: L ocal Variables (Functions) Function workspaces ◦ Local scope Variables ◦ Parameter variables live from function entry ◦ Local variables live from assignment ◦ Until function finishes (or clear) ◦ Local workspace is cleared at end of function ◦ Output copied/assigned to variables in calling workspace

Scripts vs. Functions

Why use Functions? Top-down design Encapsulation More flexible, resuable code Testing strategy

Top-down design Break a complex problem into simpler manageable problems Solve simpler problems Connect simple solutions to solve original problem Functions give your code structure

Encapsulation A function is isolated from the rest of the system, and interacts only through its input and output arguments. ◦ A function can't mess up the variables in your workspace ◦ Likewise, you can't mess up a function by changing values Much more powerful, and fewer ‘side- effects’ than scripts

Flexible, reusable code A script only solves one instance of a problem A function can solve all instances ◦ You can call hypotenuse with any values of a and b Since functions are encapsulated, this means you only need to know its interface (what it does), not its implementation (how it does it) Share your solution to a problem with others. Collaboration ◦ Team, organization, world

Easier testing If you write your program as a 500-line script, and it gives the wrong answer... ◦ Good luck with that! If you write your program as a small function that calls other functions that call other functions... ◦ Test the simplest functions first ◦ Check that functions are connected correctly

Variable number of inputs How does a function like min() work? ◦ It can take a variable number of inputs  min(x);  min(x, 1)  min(x, [], 1) varargin, nargin ◦varargin is a cell array – we’ll talk about cell arrays later ◦ The variable nargin is automatically set in the local workspace of each function, and tells you how many input variables were actually supplied to the function.

Variable number of outputs How does size() work? ◦ Can return variable number of outputs varargout, nargout ◦nargout returns the number of output arguments specified for a function.