1 / 17

Flow Control and Functions

Learn about flow control, script files, and writing functions in MATLAB. Develop a function to calculate Euclidean distance between sets of points in any number of dimensions.

kcreek
Download Presentation

Flow Control and Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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.

  3. 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 % Don't need the .m here • echo on • myscript • echo off • a 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.

  4. 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

  5. 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

  6. 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.

  7. 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 (x1,y1) and (x2,y2) is:

  8. 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.

  9. 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) error('Wrong size.') end ... 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.

  10. 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

  11. 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.

  12. 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.

  13. 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.

  14. 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

  15. 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) ...

  16. 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.

  17. 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

More Related