Flow Control and Functions

Similar documents
YOGYAKARTA STATE UNIVERSITY MATHEMATICS AND NATURAL SCIENCES FACULTY MATHEMATICS EDUCATION STUDY PROGRAM

Introduction to MATLAB

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

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

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

Introduction to MATLAB

Computational Methods of Scientific Programming

User Defined Functions

LECTURE 1. What Is Matlab? Matlab Windows. Help

HERIOT-WATT UNIVERSITY DEPARTMENT OF COMPUTING AND ELECTRICAL ENGINEERING. B35SD2 Matlab tutorial 1 MATLAB BASICS

Unix Computer To open MATLAB on a Unix computer, click on K-Menu >> Caedm Local Apps >> MATLAB.

Finding MATLAB on CAEDM Computers

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

EL2310 Scientific Programming

(Refer Slide Time: 00:50)

Introduction to MATLAB

University of Alberta

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values

EL2310 Scientific Programming

3+2 3*2 3/2 3^2 3**2 In matlab, use ^ or ** for exponentiation. In fortran, use only ** not ^ VARIABLES LECTURE 1: ARITHMETIC AND FUNCTIONS

An Introduction to Matlab5

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

Image Processing Matlab tutorial 2 MATLAB PROGRAMMING

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

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

Introduction to Matlab

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

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

TABLES AND HASHING. Chapter 13


MATLAB GUIDE UMD PHYS401 SPRING 2011

MATLAB Project: Getting Started with MATLAB

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

Matlab Introduction. Scalar Variables and Arithmetic Operators

CMPS 12A Introduction to Programming Lab Assignment 7

Getting Started with MATLAB

MATLAB - Lecture # 4

10 M-File Programming

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Essentials for Scientific Computing: Bash Shell Scripting Day 3

Operator overloading

Combinatorics Prof. Dr. L. Sunil Chandran Department of Computer Science and Automation Indian Institute of Science, Bangalore

A QUICK INTRODUCTION TO MATLAB

Matlab Primer. Lecture 02a Optical Sciences 330 Physical Optics II William J. Dallas January 12, 2005

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

More Scripting Techniques Scripting Process Example Script

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Repetition Structures Chapter 9

Chapters 6-7. User-Defined Functions

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Introduction to Matlab

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple

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

Mathworks (company that releases Matlab ) documentation website is:

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

MATLAB Functions and Graphics

MATLAB Introduction To Engineering for ECE Topics Covered: 1. Creating Script Files (.m files) 2. Using the Real Time Debugger

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

MATLAB Project: Getting Started with MATLAB

MITOCW watch?v=4dj1oguwtem

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

The Mathematics of Big Data

What is MATLAB and howtostart it up?

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Spring 2010 Instructor: Michele Merler.

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Getting started with MATLAB

EGR 111 Functions and Relational Operators

Physics 326 Matlab Primer. A Matlab Primer. See the file basics.m, which contains much of the following.

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Chapter 1 Introduction to MATLAB

SAMLab Tip Sheet #1 Translating Mathematical Formulas Into Excel s Language

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

CS1114 Assignment 5, Part 2

MAT 343 Laboratory 2 Solving systems in MATLAB and simple programming

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.

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

Lab of COMP 406 Introduction of Matlab (III) Programming and Scripts

Dr Richard Greenaway

A Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

MATLAB GUIDE UMD PHYS401 SPRING 2012

MATLAB TUTORIAL WORKSHEET

EE168 Handout #6 Winter Useful MATLAB Tips

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers & Number Systems

Boolean Logic & Branching Lab Conditional Tests

AMS 27L LAB #2 Winter 2009

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

MATLAB Introductory Course Computer Exercise Session

Lecture 15 MATLAB II: Conditional Statements and Arrays

Scripting. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

EGR 111 Functions and Relational Operators

Chapter 6: The C Preprocessor

Programming Fundamentals

(Refer Slide Time: 1:27)

COMS 3101 Programming Languages: MATLAB. Lecture 2

Computer Science 210 Data Structures Siena College Fall Topic Notes: Recursive Methods

Transcription:

Flow Control and Functions Script files If's and For's Basics of writing functions Checking input arguments Variable input arguments Output arguments Documenting functions Profiling and Debugging

Introduction Today, we are going to explore the wonderful world of functions. Functions are critical to efficiently using matlab. We are going to spend most of the class working on a single function. In each step, we will add features to this function while we learn. The end result will be a function that measures Euclidean distance between sets of points in an arbitrary number of dimensions. Before starting, I would like everyone to change their working directory to the Windows Desktop. You can either do this with the cd command, or (easier) by clicking on the... besides the Current Directory displayed at the top of the Matlab Window and selecting the desktop. We will be saving and loading any and all files from the desktop during these classes.

Script Files Before beginning our function, we need a couple more matlab tools. In matlab, any set of commands can be placed in a text file and run as a group from the Command Window. These are called script files. For example, place the following commands inside a new text file: % This is my script file [1 2 3] a = randn([2, 3]) a.^ a %%% This raises a to the a %%%% Save the file as myscript.m. All matlab script files must end in.m. To run these commands, just type the filename in the command window. Compare the following: myscript echo on myscript echo off a % Don't need the.m here echo on repeats all the commands in the script file as they are executed. In many of the following pages, it will be more convenient to place the commands inside scripts files and execute them all at once. Nevertheless, any command can be entered on the command line.

Flow Control: if Flow control refers to any command that changes the execution order of the code. These include if, for, switch and while. if is used to make a logical test. a = 4.1 * pi; if a > pi a < pi b = mod( a, 2*pi ); % Between 0 and 2*pi. if b > pi, b = b 2*pi; end % All in one line. else b = a; end Note the indentation. This is useful for reading, but not strictly necessary. All flow control blocks in matlab must end with end. The commands any and all are useful for flow control. any checks is true if any element of the vector is true, all is true only if all elements of the vector are true. a = [ 1 NaN 2]; if any( isnan( a ) ) a( isnan(a) ) = 999; end

Flow Control: for & switch for repeats a series of commands once for each element of an array. a = 1:5 for i = a disp([ 'The square of ' int2str(i) ' is '... int2str(i^2) '.' ]) end Note that i receives each of the values of a. disp is useful for displaying textual output. switch is shorthand for various if statements. It is particularly useful with strings. loo.status = 'bad'; switch loo.status case 'bad' loo.grade = 1; case 'good' loo.grade = 4; otherwise loo.grade = 999; end

Function Basics Here we are going to begin with functions. The basic form of a matlab function is: function [out1,out2,...]=f_name(in1,in2,...) % Documentation (PUT YOUR CODE HERE) where in and out are the input and output arguments. Functions are saved in m files with the same name as the function. They are used from the command window in the same way one would use any matlab function (mean, size,...). Inside a matlab function, the only known variables are those in the function. Variables defined in the Command Window are absent inside the function. Here is a simple example that divides one number by another and returns the integer divisor and its remainder: function [id,r] = divideme( n, d ) % DIVIDEME % This function does division like you did in grammar % school. id = floor( n/d ); r = n id * d; This function would be saved in a file with the name divideme.m and would be called from the command line as divideme. Try it and see that it works.

Our Function As promised, we are going to be creating our own function in this class. I would like you to create a function that measures Euclidean distance between vectors of points. For example, suppose you have measured the x,y coordinates of three jetties, as well as the position of 20 different buoys, and you wish to know the distance from any of the jetties to any of the buoys. The jetty positions would be a 3x2 array (first column for x, second for y), the buoy positions would be a 20x2 array. The result of the function is a 3x20 matrix with the distance from any jetty to any buoy. Try to create this function. Begin with a function that expects coordinates in 2 dimensions (2 column matrices). The function should begin something like: function [ d ] = dist( coord1, coord2 )... An efficient solution to the problem will probably use the transpose operator and the functions size and repmat. Don't hesitate to check out the help for these functions. Use your matrix arithmetic. The formula for the Euclidean distance between a pair of points (x 1,y 1 ) and (x 2,y 2 ) is: x 1 x 2 2 y 1 y 2 2

Solution 1 Please try to work this problem out on your own. If you are really having problems, click here for a solution to the problem as this stage of development. If this link does not work, try at the end of the page.

Checking Input Arguments Typically in a function you want to make sure that the correct type of arguments are passed to the functions. In our example, you want to make sure that the first and second arguments have the same number of columns, and that that number is 2. If not, you should return an error.... if (size(coord1,2) ~= size(coord2,2))... (size(coord1,2) ~= 2) end... error('wrong size.') The error exits the function immediately and displays the given string. Add these lines to your function and see how they work. You can also place return anywhere in your function to exit the function early without an error.

Variable Input Arguments Matlab does not automatically complain if the number of input arguments given to a function is less than the number expected. Matlab simply leaves the extra input variables undefined. This is useful for allowing variable numbers of input arguments. Inside a matlab function, there is a predefined variable, nargin, which tells you how many input variables were actually given. Try using the following function with several different numbers of input arguments: function r = test( a, b, c, varargin ) r = nargin; Note the use of varargin. This allows you to have any number of input arguments. All extra input arguments are placed in a cell array called varargin. In the above function, varargin{1} would be the fourth input argument, varargin{2} would be the fifth, etc. Try adding the following to your function so that it works with only one input argument: if nargin < 2, coord2 = coord1; end

Our Function 2 You now have the necessary information to expand your function to accept coordinates in an arbitrary number of dimensions. coord1 and coord2 will no longer have two columns, but rather an arbitrary (but equal) number of columns. There are probably many solutions to this problem, but the two most straightforward are either to use a for loop, or to use repmat and shiftdim and work with 3 dimensional matrices. Don't forget to check your arguments and allow for only one input argument.

Solution 2 Click here for a solution to the problem as this stage of development. If this link does not work, try at the end of the page.

Output Arguments Much of what has been said about input arguments can also be said about output arguments. You can check how many output arguments the user requested using nargout. Large numbers of output arguments can be accommodated using varargout. Change the dist function as follows so that it will, if desired, return a second output argument with the dimension of the input vectors: function [d, dim]=dist(coord1,coord2)... if nargout > 1, dim = size(coord1,2); end Test the function with zero, one and two output arguments.

Documenting Functions Creating help documentation for personal functions in matlab is extremely easy and useful. All you have to do is include comment lines right after the function line. Change the beginning of your function so that it looks as follows: function [d, dim]=dist(coord1,coord2) % DIST a function that measures distances % % Usage: d = dist( coords1, coords2 ) % [d, dim] = dist( coords1, coords2 ) % If coords1 is a MxN matrix and coords2 is a PxN matrix, % then the result is an MxP matrix of Euclidean distances % between the vectors in R^N given in coords1 and coords2 Now try the following from the command window: help dist which dist

Subfunctions Matlab functions can contain their own private subfunctions simply be tacking these subfunctions onto the end of the file. For example, one rather clean way to solve the distance function problem in arbitrary dimensions is to use a subfunction that computes the distance squared in one dimension and then use a for loop to pass over each dimension. It would look something as follows: function [d, dim]=dist(coord1,coord2)... d = d + dist1sq(coord1(:,i),coord2(:,i));... d = sqrt(d)... function d = dist1sq(c1,c2)...

Final Solution Click here for the final version of the function as I would have written it. If this link doesn't work, look for a link at the end of the slide. Again, this is only one possible way to solve the problem. Yours might look totally different but function all the same. My version has the benefit of being reasonably fast while minimizing memory usage in higher dimensions.

Debugging and Profiling Matlab makes it fairly easy to debug functions. Debugging begins with the error messages it prints out on failure, but goes far beyond that. It is a fairly complex topic, so I won't say much. The simplest tool you can use is the keyboard command. This command, when placed inside a function, temporarily exits the function and allows the user to examine variables inside the function, step through the function (see dbstep) and continue when desired (see return). Another useful and entertaining thing to do is profile a function. This is a way of keeping track of how much time matlab spends in different parts of your function. In this way, you can see what parts of the function take the longest and concentrate your efforts on improving those parts. Try the following: a = randn( 1000, 2 ); b = randn( 1000, 2 ); profile on dist( a, b ); profile report