CS112 Scientific Computation Department of Computer Science Wellesley College Building your own Functions.

Slides:



Advertisements
Similar presentations
Lecture 5.
Advertisements

CSE 123 Plots in MATLAB. Easiest way to plot Syntax: ezplot(fun) ezplot(fun,[min,max]) ezplot(fun2) ezplot(fun2,[xmin,xmax,ymin,ymax]) ezplot(fun) plots.
Introduction to Engineering MATLAB – 11 Plotting - 4 Agenda Multiple curves Multiple plot.
Modular Programming With Functions
Plotting Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to Matlab
Matlab Graphics S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: 2D Graphics.
Lab5 (Signal & System) Instructor: Anan Osothsilp Date: 20 Feb 07 Due Date 09 March 07.
MATLAB - Basics Centro de Informática Universidade Federal de Pernambuco Aprendizagem de Máquina – IN1102 Arley Ristar –
Chapter 3: Modularization
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
MATLAB’s extensive, device-independent plotting capabilities are one of its most powerful features. They make it very easy to plot any data at any time.
CS 201 Functions Debzani Deb.
1 Modularity In “C”. 2 What is Modularity?  Modularity, is the heart of the high level, structured languages.  Means breaking down a big problem into.
CS 201 Functions Debzani Deb.
Chapter 8: Introduction to High-level Language Programming Invitation to Computer Science, C++ Version, Third Edition.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Dr. Jie Zou PHY Welcome to PHY 3320 Computational Methods in Physics and Engineering.
Chapter 8: Introduction to High-Level Language Programming Invitation to Computer Science, C++ Version, Fourth Edition.
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.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
CS112 Scientific Computation Department of Computer Science Wellesley College Cold Coffee Vectors and plotting.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
CS110: Computers and the Internet Getting Started Orit ShaerOrit Shaer, Scott Anderson, Sohie Lee, Jean Herbst.
CS112 Scientific Computation Department of Computer Science Wellesley College Matrices Storing two-dimensional numerical data.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
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.
COMP 116: Introduction to Scientific Programming Lecture 5: Plotting, Scripts and publishing.
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.
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
CS112 Scientific Computation Department of Computer Science Wellesley College Hodgepodge “Clumsy mixture of ingredients…”
1 E0001 Computers in Engineering Built in Functions.
NA2204.1jcmt CSE 1320 Intermediate Programming C Program Basics Structure of a program and a function type name (parameters) { /* declarations */ statement;
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
COMP 116: Introduction to Scientific Programming Lecture 36: Final Review I.
CS112 Scientific Computation Department of Computer Science Wellesley College Building your own Functions.
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.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 4: Computation 1 Based on slides created by Bjarne Stroustrup.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
CS112 Scientific Computation Department of Computer Science Wellesley College Loops Iteration with for loops.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
CS112 Scientific Computation Department of Computer Science Wellesley College Interactive Programs Graphical User Interfaces.
CS112 Scientific Computation Department of Computer Science Wellesley College Tables More matrix fun.
Matlab Tutorial Iman Moazzen First Session – September 11, 2013.
CS112 Scientific Computation Department of Computer Science Wellesley College Vectors and indexing Tools of the trade.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
1 Lecture Three I/O Formatting and Arithmetic Dr. Sherif Mohamed Tawfik.
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
Computer Application in Engineering Design
Lecture: MATLAB Chapter 1 Introduction
Chapter 6 Functions.
About the Presentations
Functions CIS 40 – Introduction to Programming in Python
“Clumsy mixture of ingredients…”
Cold Coffee Vectors and plotting
Chapter 8: Introduction to High-Level Language Programming
Matlab review Matlab is a numerical analysis system
Functions, Procedures, and Abstraction
Programming We have seen various examples of programming languages
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.
Top-Down Design with Functions
Programming The ideal style of programming is Structured or
Introduction to Methods and Interfaces
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

CS112 Scientific Computation Department of Computer Science Wellesley College Building your own Functions

8-2 Three big ideas Programmers use three important concepts to help manage the complexity of their projects: Abstraction Modularity Divide, Conquer and Glue ENIAC

Functions8-3 Big idea number 1: Abstraction Function Black Box Sohie You Implementer / Designer User / Client Contract

Functions8-4 Big idea number 2: Modularity Large systems are built from components called modules Modules may capture parts of the task that could be re-used in other contexts The interfaces between modules are designed so they can be put together in a mix-and-match way

Functions8-5 Big idea number 3: Divide, conquer & glue P P1P1 P2P2 P3P3 P4P4 S4S4 S3S3 S2S2 S1S1 S Divide problem P into subproblems Conquer each of the subproblems Glue combine the solutions to the subproblems into a solution S for P

Functions8-6 Functions help us to do all three Functions encapsulate code for performing common tasks Functions help us to hide programming details and modularize our programs Functions help us to manage the divide-conquer-and-glue strategy

Functions8-7 Built-in MATLAB functions math:sum, prod, mean, std, abs, sqrt, sin, cos, abs, exp, min, max logical:any, all, and, or, not creation:linspace, colon, ones, zeros dimensions: size, length graph/display: plot, figure, subplot, xlabel, ylabel, title, axis, legend, imshow, imtool input/output: input, disp

Functions8-8 The other side of the contract We’ve been using functions built by others - let’s try writing a few of our own Implement a myMean function that returns a single value representing the average value of a vector or matrix

Functions8-9 Rules of the road function avg = myMean (data) % avg = myMean(data) % returns the average of all of the values % in data, which may be a vector or matrix dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end output parameter function name (stored in file myMean.m) input parameter help comments contract function body assign output local variable* * Local variables only exist during the execution of the function keyword

Functions8-10 Calling the new myMean function >> nums = [ ]; >> meanVal = myMean(nums) meanVal = >> nums = [3 4 7; 2 8 6] nums = >> meanVal = myMean(nums) meanVal =

Functions8-11 Executing a function MATLAB workspace Execution land >>

Functions8-12 Create nums vector MATLAB workspace Execution land >> nums = [ ]; nums 39628

Functions8-13 Assignment statement MATLAB workspace Execution land >> nums = [ ]; >> meanVal = myMean(nums) nums meanVal

Functions8-14 Invoke myMean function MATLAB workspace Execution land >> nums = [ ]; >> meanVal = myMean(nums) nums meanVal myMean local workspace function avg = myMean(data) dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end

Functions8-15 Create variables for input parameters MATLAB workspace Execution land >> nums = [ ]; >> meanVal = myMean(nums) nums meanVal myMean local workspace data function avg = myMean(data) dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end

Functions8-16 Assign input parameters to call values MATLAB workspace Execution land >> nums = [ ]; >> meanVal = myMean(nums) nums meanVal myMean local workspace data function avg = myMean(data) dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end

Functions8-17 Execute function body MATLAB workspace nums meanVal myMean local workspace data Execution land >> nums = [ ]; >> meanVal = myMean(nums) function avg = myMean(data) dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end dims 15

Functions8-18 Is min(dims) == 1? MATLAB workspace nums meanVal myMean local workspace data Execution land >> nums = [ ]; >> meanVal = myMean(nums) function avg = myMean(data) dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end dims 15

Functions8-19 Yes, so we do 'then' clause MATLAB workspace nums meanVal myMean local workspace data Execution land >> nums = [ ]; >> meanVal = myMean(nums) function avg = myMean(data) dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end dims 15 avg 5.60

Functions8-20 Return value stored in output variable MATLAB workspace nums meanVal myMean local workspace data Execution land >> nums = [ ]; >> meanVal = myMean(nums) function avg = myMean(data) dims = size(data); if (min(dims) == 1) avg = sum(data)/length(data); else avg = sum(sum(data))/prod(dims); end dims 15 avg 5.60

Functions8-21 And the local workspace goes away MATLAB workspace nums meanVal Execution land >> nums = [ ]; >> meanVal = myMean(nums) meanVal =

Functions8-22 Try another one? Write a function to draw a circle Think first about the contract: use inputs to control appearance: radius, location, color, markers, line style, line width Call the new function drawCircle and store it in an M-File named drawCircle.m

Functions8-23 Getting started function drawCircle (radius, xcenter, ycenter, properties, width) % drawCircle(radius, xcenter, ycenter, properties, width) % draws circle with the specified radius, centered on location % (xcenter, ycenter) with the specified properties and width don’t forget contract comments!

Functions8-24 Filling in the function body function drawCircle (radius, xcenter, ycenter, properties, width) % drawCircle(radius, xcenter, ycenter, properties, width) % draws circle with the specified radius, centered on location % (xcenter, ycenter) with the specified properties and width angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); plot(xcoords, ycoords, properties, 'LineWidth', width);

Functions8-25 Executing drawCircle function Execution land >> drawCircle(40, 50, 50, 'g-*', 1); MATLAB workspace

Functions8-26 MATLAB workspace Execution land >> drawCircle(40, 50, 50, 'g-*', 1); function drawCircle (radius, xcenter, ycenter, … properties, width) angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); plot(xcoords, ycoords, properties,... 'LineWidth', width); Create input parameter variables... drawCircle local workspace radius xcenter ycenter properties width

Functions8-27 MATLAB workspace Execution land >> drawCircle(40, 50, 50, 'g-*', 1); function drawCircle (radius, xcenter, ycenter,... properties, width) angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); plot(xcoords, ycoords, properties,... 'LineWidth', width);... and fill them in from call statement drawCircle local workspace radius 40 xcenter 50 ycenter 50 properties g-* width 1

Functions8-28 MATLAB workspace Execution land >> drawCircle(40, 50, 50, 'g-*', 1); function drawCircle (radius, xcenter, ycenter,... properties, width) angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); plot(xcoords, ycoords, properties,... 'LineWidth', width); Execute body of function drawCircle local workspace radius 40 xcenter 50 ycenter 50 properties g-* width 1 angles …

Functions8-29 MATLAB workspace Execution land >> drawCircle(40, 50, 50, 'g-*', 1); function drawCircle (radius, xcenter, ycenter,... properties, width) angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); plot(xcoords, ycoords, properties,... 'LineWidth', width); Next statement drawCircle local workspace radius 40 xcenter 50 ycenter 5 properties g-* width 1 angles xcoords … …

Functions8-30 MATLAB workspace Execution land >> drawCircle(40, 50, 50, 'g-*', 1); function drawCircle (radius, xcenter, ycenter,... properties, width) angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); plot(xcoords, ycoords, properties,... 'LineWidth', width); Next statement drawCircle local workspace radius 40 xcenter 50 ycenter 5 properties g-* width 1 angles xcoords … … ycoords …

Functions8-31 MATLAB workspace Execution land >> drawCircle(40, 50, 50, 'g-*', 1); function drawCircle (radius, xcenter, ycenter,... properties, width) angles = linspace(0, 2*pi, 50); xcoords = xcenter + radius * cos(angles); ycoords = ycenter + radius * sin(angles); plot(xcoords, ycoords, properties,... 'LineWidth', width); And we draw the circle drawCircle local workspace radius 40 xcenter 50 ycenter 5 properties g-* width 1 angles xcoords … … ycoords …

Functions8-32 MATLAB workspace Execution land >> drawCircle(40, 50, 50, 'g-*', 1); Where’d everybody go?

Functions8-33 A thorough test % testCircle.m % tests the drawCircle function hold on drawCircle(40, 50, 50, 'g-*', 1); drawCircle(20, 40, 60, 'b:^', 2); drawCircle(25, 30, 40, 'r-.s', 2); legend('one', 'two', 'three'); drawCircle(10, 20, 20, 'm--o', 1); axis equal axis([ ]) hold off

Functions8-34 Functions with multiple outputs Suppose we’d like to write a variation of myMean that returns both the arithmetic mean and geometric mean Given n numbers: a 1, a 2 … a n arithmetic mean: (a 1 + a 2 + … + a n )/n geometric mean: √ a 1 * a 2 * … * a n n

Functions8-35 Consider first... Some built-in functions can return one or more values, depending on how the function is called For example, consider the min function: >> nums = [ ]; >> minVal = min(nums) minVal = 2 >> [minVal minIndex] = min(nums) minVal = 2 minIndex = 4

Functions8-36 New lean mean machine function [arith geom] = myMean2(data) % [arith geom] = myMean2(data) % returns both the arithmetic and geometric mean of % the values in data, which may be a vector or matrix dims = size(data); if (min(dims) == 1) arith = sum(data)/length(data); geom = nthroot(prod(data), length(data)); else arith = sum(sum(data))/prod(dims); geom = nthroot(prod(prod(data)), prod(dims)); end

Functions8-37 Credit Eniac: US Army photo from the archives of the ARL Technical Library