2 Goals Top down design Introduction Functions M file structure Functions workspaceFunctions Input and outputTop down designLocal functionsDebuggerRecursionMore:Functions and commandsFunctions and the matlab search path
3 Function Is an Independent Piece of Code Which Performs a Task Function (subroutine, method, procedure, or subprogram) –is a portion of code within a larger program,which performs a specific task andcan be relatively independent of the remaining code.One M-file, One Task, One Workspace
4 Variables - The Data Objects, Functions Are The Actions Input (Object / Data):X =809095100988892Functions:y = mean(x)y = sum(x)y = max(x)Output: (Data)91.85643100
5 A Function Is a Black Box OutputInputfunctionA function is a black boxIt hides the code and its workspace and communicates with the “world” using the input and output variables55
6 Functions M file structure The file is a Matlab functionThe output variables (if there are few use : [out1 out2] )Should be same as the name of the filesumTwoNums.m:function my_sum = sumTwoNums(a,b)my_sum = a+b;The input variablesAssign the output variables(else - Matlab will give an error)
7 Functions Documentation and Variable Verification function my_sum = sumTwoNums(a,b)% SUMTWONUMS sum to scalars% this function sums two scalar% and returns the result% INPUT:% a - the first scalar% b - the second scalar%% OUTPUT:% my_sum - the sum of a and b; sum = a+bif (~isscalar(a))error('First argument is not a scalar');endif (~isscalar(b))error('Second argument is not a scalar');my_sum = a+b;First linehelp:UsageInputOutputExamplesTesting for proper variablesCalculations and Output assignment
8 Each Instance of A Function Run Has Its Own Workspace Assume we wrote the function:function my_sum = sumTwoNums(a,b)my_sum = a + b;In the workspace we run:a = 1;b = 2;x = 3;y = 4;s = sumTwoNums(x, y)What is the output?s = 7MatlabWorkspace:a = 1b = 2X = 3y = 4s = 7Function Workspace:a = 3b = 4my_sum = 7
9 Matlab Functions Can Be Called With Fewer Input Arguments Than Specified Consider a function that computesfunction y = calSecondOrderPoly(x, a, b, c)switch nargincase 4% do nothingcase 3c = 0;case 2b = 0;otherwiseerror('Incorrect input');endy = a*x.^2 + b*x + c;Switch according to input arguments numberDefault value
10 Matlab Functions Can Be Called With Fewer Output Arguments Than Specified Recall:[r,c] = find(A) , ind = find(A);sorted_A= sort(A); [sorted_A, sort_ind] = sort(A);Now lets improve our function such that if it called with two output arguments, the second argument is the derivative:[y, y_derivative] = calSecondOrderPoly(x, a, b, c);
11 Matlab Functions Can Be Called With Fewer Output Arguments Than Specified function [y, y_derivative] = calSecondOrderPoly(x, a, b, c)y = a*x.^2 + b*x + c;if nargout == 2y_derivative = 2*a*x + b;endChecks number of output argumentsCan help avoid expensive computations when they are not necessary
12 Example - Write a function subtractTwoNums Add Help to the function Input: a, bOutput: a-bAdd Help to the functionTry calling the function (Debugger)*Extra: if the function needs to return two output variables:Output: [a-b, b-a]
13 Top Down Design A method to solve complex problems Principles: Start from large problems to smallA function does one taskThink before you code
14 Top Down Design and Debugging – Tic-Tac-Toe Example Problem specifications:Build a tic-tac-toe game for two players.
15 Lets break the problem top-down Play Tic-Tac-ToeHave somegame matrixGet Next MoveCheck for a winnerInitiate thegame matrixGet columnGet rowAnnounce the winnerUpdate thegame matrixCheck whetherthe move is legalDisplay thegame matrix
16 Choosing the Data Structures We will use two game matricesWarning: We use it here for simplicity, usually it is better to avoid data duplication“Num_mat” - 3x3 numeric matrix“display_mat” - 3x9 char matrix1NaN2‘ X ‘‘ – ‘‘ O ‘
17 Writing the functions – “Go with the (control) flow” Play Tic-Tac-ToeInitiate game matrixInitiate “who won flag” variable to 0Initiate “current player flag” variable to 1Loop 9 times (for i=1:9):Get Next MoveUpdate game matrixDisplay game matrixCheck for winner – if found a winner:Update “who won flag” (1 or 2) and BreakSwitch the “current player flag” 1<->2Announce winner according to the “who won flag” variableA“Flags” –A variable which holds informationabout the program statusand helps you control the flowGet rowGet columnCheck if it is a legal move
19 Debugging Run Time Errors Our weapons:Break points –RedGrayModifying a fileDebug buttonsDebug menuStop if errors / warnThere are two bugsLets find them . .To the code!
20 Error Syntax errors – Runtime errors – Lets try to run playTicTacToe func1;function func1()func2()Syntax errors –Lets try to run playTicTacToeRuntime errors –You can plant in the code disp() massages that will help you debug.You should use errors when the input of the function is not validDebugger …function func2()Tryfunc3();Catchdisp(‘Caught’);endfunction func3()func4()function func4 ()A = ones(1,1);B = A(1,2);
21 Recursion – factorial example I don’t know what is factorial of 3But I know it is 3 multiply the factorial of 2function res = myFactorial(x)% check: x is a non-negative integerif (x == 0 || x == 1)res = 1;elseres = x * myFactorial(x-1);endI don’t know what is factorial of 2But I know it is 2 multiply the factorial of 1Ah ha!The factorial of 1 is 1!
22 Summary Top down design Introduction Functions M file structure Functions workspaceFunctions Input and outputTop down designLocal functionsDebuggerRecursionMore:Functions and commandsFunctions and the matlab search path