Chapter 6 User-Defined Functions. dr.dcd.h CS 101 /SJC 5th Edition 1

Similar documents
Example: A Four-Node Network

9/4/2018. Chapter 2 (Part 1) MATLAB Basics. Arrays. Arrays 2. Arrays 3. Variables 2. Variables

Chapters 6-7. User-Defined Functions

User Defined Functions

Introduction. Like other programming languages, MATLAB has means for modifying the flow of a program

22-Functions Part 1 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

W1005 Intro to CS and Programming in MATLAB. Data Structures. Fall 2014 Instructor: Ilia Vovsha. hep://

What is a Function? EF102 - Spring, A&S Lecture 4 Matlab Functions

User-defined Functions

Scientific Computing with MATLAB

Matlab Advanced Programming. Matt Wyant University of Washington

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221

Computational Methods of Scientific Programming

APPM 2460 Matlab Basics

INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD. July 2018

Lecture 6 MATLAB programming (4) Dr.Qi Ying

FUNCTIONS ( WEEK 5 ) DR. USMAN ULLAH SHEIKH DR. MUSA MOHD MOKJI DR. MICHAEL TAN LONG PENG DR. AMIRJAN NAWABJAN DR. MOHD ADIB SARIJARI

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

Tentative Course Schedule, CRN INTRODUCTION TO SCIENTIFIC & ENGINEERING COMPUTING BIL 108E, CRN24023 LECTURE # 5 INLINE FUNCTIONS

Flow Control and Functions

Quiz 1: Functions and Procedures

COMS 3101 Programming Languages: MATLAB. Lecture 2

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

MATLAB Demo. Preliminaries and Getting Started with Matlab

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Introduction to Programming in MATLAB

MATLAB Project: Getting Started with MATLAB

COGS 119/219 MATLAB for Experimental Research. Fall Functions

Question Points Score Total 100

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

ME313 Homework #5. Matlab- Functions

To start using Matlab, you only need be concerned with the command window for now.

Matlab- Command Window Operations, Scalars and Arrays

Lecture 8 Programmer-Defined Functions in MATLAB

Informal Reference Manual for X

CS1132 Fall 2009 Assignment 1. 1 The Monty Hall Dillemma. 1.1 Programming the game

1 Introduction to Matlab

Introduction to Matlab

EL2310 Scientific Programming

Assignment 2 in Simulation of Telesystems Laboratory exercise: Introduction to Simulink and Communications Blockset

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

CS 113: Introduction to

Lecture 4: Complex Numbers Functions, and Data Input

Homework 5. Due Friday, March 1 at 5:00 PM

Finding, Starting and Using Matlab

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Excel Formulas & Functions I CS101

CS : Programming for Non-Majors, Fall 2018 Programming Project #5: Big Statistics Due by 10:20am Wednesday November

MATLAB Project: Getting Started with MATLAB

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Homeworks on FFT Instr. and Meas. for Communication Systems- Gianfranco Miele. Name Surname

Introduction to MATLAB

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson)

Ph3 Mathematica Homework: Week 1

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Introduction to Matlab

Objectives of This Chapter

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS129: Introduction to Matlab (Code)

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y

INTRODUCTION TO MATLAB

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

10 M-File Programming

Spring 2010 Instructor: Michele Merler.

LAB 2: Linear Equations and Matrix Algebra. Preliminaries

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.

CSC 121: Computer Science for Statistics

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

The Mathcad Workspace 7

Lecture 4. Defining Functions

1 Overview of the standard Matlab syntax

Chemical Engineering 541

Table of contents. HTML5 Data Bindings Repeater DMXzone

Introduction to MATLAB

The Dynamic Typing Interlude

Reset-able and Enable-able Registers

University of Alberta

CS1132 Spring 2016 Assignment 2 Due Apr 20th

Lecture 20 Transactions

Introduction to Bottom-Up Parsing

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Functions and text files

Lecture 3: C Programm

11/3/71 SYS BREAK (II)

Transactions. CS 475, Spring 2018 Concurrent & Distributed Systems

Working with the Soft Properties Manager

Lab 1 Introduction to MATLAB and Scripts

Review: Classes and Object Instances. Review: Creating an Object. Using Multiple Objects. DrawingGizmo pencil; pencil = new DrawingGizmo();

Getting started with MATLAB

Lab 8: Conditional Statements with Multiple Branches (please develop programs individually)

ENGR 105: Introduction to Scientific Computing. Dr. Graham. E. Wabiszewski

Chapter 5 Errors. Bjarne Stroustrup

S206E Lecture 19, 5/24/2016, Python an overview

EW7 Assignment: (FCN) Functions

Master of Science in Engineering 29 September 2004 University of Uppsala 29 September Wanda for MATLAB

Transcription:

Chapter 6 User-Defined Functions dr.dcd.h CS 101 /SJC 5th Edition 1

MATLAB Functions M-files are collections of MATLAB statements that stored in a file, called a script file. Script files share the command window s workspace, so any variables created by the script files remain in the workspace after the script file finishes executing. A script file has no input arguments returns no results, but they communicate through the data left behind in the workspace. dr.dcd.h CS 101 Spring 2009 2

MATLAB Functions 2 A MATLAB function is a special type of M- file that runs in its own independent workspace. A MATLAB function receives input data through an input argument list and returns results to the caller through an output argument list. A MATLAB function should be placed in a file with the same name as the function with an extension of.m. dr.dcd.h CS 101 Spring 2009 3

MATLAB Functions 3 A function consists of three components For example: a = cos(x) output argument function name input argument All functions, whether they are build-in or user-defined functions, are available for any M-file programs dr.dcd.h CS 101 Spring 2009 4

Syntax The general form of a function as function [outarg1, outarg2, ] = funcname(inarg1, inarg2, ) % H1 % other comments Function statements (return/end) The function keyword marks the beginning of the function. If there are only one output argument, the brackets can be dropped. Input arguments are placeholders for values. dr.dcd.h CS 101 Spring 2009 5

Syntax 2 The comments block following the function statement is called the help block. The first line of it is called the H1. It should contain a one-line summary of the purpose of the function. H1 will be searched and displaced by lookfor, while the whole help block will be displaced if the command help keyword is used. Execution begins at the top and ends when either a return, an end, or the end of the function is reached. dr.dcd.h CS 101 Spring 2009 6

Syntax 3 For debugging purpose, it may be useful to print intermediate results to the command window. However, once you complete your debugging make sure that all your output is suppressed. If you don t, you ll see extraneous information in the command window. It means that you should use ; at the end of every statement. dr.dcd.h CS 101 Spring 2009 7

Pass-by-Value When a function is called, MATLAB makes a copy of the actual arguments and passes them to the workspace of the function. If the passed arguments are modified, it won t affect the original data in the caller. Command window s workspace x = 5; a = abc(x) cw.x abc.x Function abc s workspace function out=abc(in) abc.in abc.x dr.dcd.h CS 101 Spring 2009 8

Local Variables Variables defined in an M-file function, only have meaning inside that program. The only way to communicate between functions and the workspace, is through the function input and output arguments. dr.dcd.h CS 101 Spring 2009 9

Example 1: dist2(x 1,y 1,x 2,y 2 ) The distance between two points (x 1, y 1 ) and (x 2, y 2 ) can be defined as dr.dcd.h CS 101 Spring 2009 10

H1 & Help Block After applying help and lookfor, function dist2 provides the following results. dr.dcd.h CS 101 Spring 2009 11

Example 2: [x,y]=polar2rect(r,q) Convert polar coordinates (r,q) to rectangular form (x,y). dr.dcd.h CS 101 Spring 2009 12

Example 3: [r,q]=rect2polar(x,y) Convert rectangular coordinates (x,y) to polar form (r,q). dr.dcd.h CS 101 Spring 2009 13

Example 4: Selection Sort State the problem. Sort the data into ascending or descending order using the selection sort algorithm. Define the input/output. The inputs are typed by the user, and the outputs are the sorted data written to the command window. Describe the algorithm. - Input an array of n values; - Set the index i equals to1; - Scan and locate the i-th minimum value; - Swap the i-th minimum with the i-th element; - repeat n-1 times. dr.dcd.h CS 101 Spring 2009 14

Example 4: Selection Sort 2 dr.dcd.h CS 101 Spring 2009 15

Optional Arguments Some function may support arbitrary numbers of arguments. For example: plot(x, y); plot(x, y, :ok ); Plot(x, y, :ok, MarkerSize, 3); Functions that can be used to furnish optional arguments nargin, nargout, nargchk varargin, varargout error, warning inputname dr.dcd.h CS 101 Spring 2009 16

Optional Arguments 2 nargin: the number of actual input arguments. nargout: the number of actual output arguments. nargchk: this function returns an error message if too few or too many arguments are used. - syntax: nargchk(min, max, nargin) varargin: the list of variables for actual input arguments. varargout: the list of variables for actual output arguments. dr.dcd.h CS 101 Spring 2009 17

Optional Arguments 3 error: display an error message and abort if a fatal error was caught when a function is called. If its input argument is an empty string, then it does nothing. warning: display a warning message and resume the execution of a function. inputname: this function returns the actual name of the dummy argument. dr.dcd.h CS 101 Spring 2009 18

Optional Arguments 4 dr.dcd.h CS 101 Spring 2009 19

Homework Assignment #12 Quiz 6.1 Page 251: 6, 7 This assignment is due by the next week. Late submission will be penalized. dr.dcd.h CS 101 Spring 2009 20

Global Memory MATLAB functions can also exchange data with each other with the base workspace through global memory. Global memory is a specifal type of memory that can be accessed from any workspace. A global variable is declared as global variable The default value for a global variable is empty, so an initialization is required. dr.dcd.h CS 101 Spring 2009 21

Global Memory 2 An example: To count how many time a function is called. An alternative example: Two functions are used to modify a global counter. dr.dcd.h CS 101 Spring 2009 22

Global Memory 3 dr.dcd.h CS 101 Spring 2009 23

Random Number Generator It is important to know that the real world does not provide perfect measurements. So the ideal simulated data needs to add some random noise. The simulated noise is usually created by a random number generator. The build-in random number generator function rand generates values in the range of [0.0, 1.0). Then the generated noise values can be scaled and leveled. dr.dcd.h CS 101 Spring 2009 24

Random Number Generator 2 The random numbers are in fact generated by a deterministic function; i.e. the sequence of numbers are fixed. The function returns a different and apparently random number each time it is called. It is because the function has started at a different starting point internally each time it is called. The starting point is called a seed and it is set as a global valable. dr.dcd.h CS 101 Spring 2009 25

Random Number Generator 3 Example: two set of random numbers in the range of [-0.5, 0.5]. dr.dcd.h CS 101 Spring 2009 26

Example 6.4: User Defined Random Number Generator A simple random number generator can be defined by the following equation: n 1 = a random seed n i+1 = mod(8121*n i +28411, 134456) ran i = n i 134456 where 134456 is the total highest number in the sequence and each new n i+1 is set as the next seed. dr.dcd.h CS 101 Spring 2009 27

Example 6.4: User Defined Random Number Generator 2 dr.dcd.h CS 101 Spring 2009 28

Example 6.4: User Defined Random Number Generator 3 dr.dcd.h CS 101 Spring 2009 29

Persistent Memory When a function finishes executing, the workspace created for that function is destroyed, so all local variables within that workspace will disappear. The next time the same function is called, a new workspace will be created. Sometimes, it is necessary to preserve local variables between calls to a function. dr.dcd.h CS 101 Spring 2009 30

Persistent Memory 2 Persistent memory is a special mechanism to allow local variables to be preserved between calls to a function. Syntax: persistent variable dr.dcd.h CS 101 Spring 2009 31

Persistent Memory 3 To rewrite a previous example: To count how many time a function is called. dr.dcd.h CS 101 Spring 2009 32

Persistent Memory 4 How to reset the associated counter? dr.dcd.h CS 101 Spring 2009 33

Homework Assignment #13 6.9 Exercises Page 268: 6.6, 6.7, 6.14 This homework is for your reference. dr.dcd.h CS 101 Spring 2009 34