22
Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 7: Functions and Program Design Please change directory to directory E:\Matlab (cd E:\ Matlab;) From the course website ( http://www.weizmann.ac.il/midrasha/courses/MatlabIntro//course _outline.htm ) Download:

Introduction_to_Matlab_Tutorial_7.ppt

  • Upload
    kdodo

  • View
    215

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Introduction_to_Matlab_Tutorial_7.ppt

Weizmann 2010 © 1

Introduction to Matlab & Data Analysis

Tutorial 7: Functions and Program Design

Please change directory to directory E:\Matlab (cd E:\Matlab;)

From the course website

(http://www.weizmann.ac.il/midrasha/courses/MatlabIntro//course_outline.htm )

Download:

playTicTacToe.m , isLegalMove.m , isPlayerWon.m, getNextMove.m, myFactorial.m

Page 2: Introduction_to_Matlab_Tutorial_7.ppt

2

Goals Introduction Functions M file structure Functions workspace Functions Input and output Top down design Local functions Debugger Recursion More:

Functions and commands Functions and the matlab search path

Page 3: Introduction_to_Matlab_Tutorial_7.ppt

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 and can be relatively independent of the remaining code.

One M-file, One Task, One Workspace

Page 4: Introduction_to_Matlab_Tutorial_7.ppt

4

Variables - The Data Objects, Functions Are The Actions

80 90 95 100 98 88 92X =

Input (Object / Data):

Functions:

y = mean(x) y = sum(x) y = max(x)Output: (Data) 91.85 643 100

Page 5: Introduction_to_Matlab_Tutorial_7.ppt

5

A Function Is a Black Box

5

InputOutput function

A function is a black box

It hides the code and its workspace and communicates with the “world” using the input and output variables

Page 6: Introduction_to_Matlab_Tutorial_7.ppt

6

Functions M file structure

function my_sum = sumTwoNums(a,b) my_sum = a+b;

The file is a Matlab function

The output variables (if there are few use []: [out1 out2] )

Assign the output variables

(else - Matlab will give an error)

Should be same as the name of the file sumTwoNums.m:

The input variables

Page 7: Introduction_to_Matlab_Tutorial_7.ppt

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+b if (~isscalar(a)) error('First argument is not a scalar');endif (~isscalar(b)) error('Second argument is not a scalar');end

my_sum = a+b;

First line help:

Usage

Input

Output

Examples

Testing for proper variables

Calculations and Output assignment

Page 8: Introduction_to_Matlab_Tutorial_7.ppt

8

Each Instance of A Function Run Has Its Own Workspace

In the workspace we run:

a = 1;b = 2;x = 3;y = 4;s = sumTwoNums(x, y)What is the output?s = 7

function my_sum = sumTwoNums(a,b)my_sum = a + b;

Assume we wrote the function:

Matlab

Workspace:

a = 1

b = 2

X = 3

y = 4

s = 7

Function Workspace:

a = 3

b = 4

my_sum = 7

Page 9: Introduction_to_Matlab_Tutorial_7.ppt

9

Matlab Functions Can Be Called With Fewer Input Arguments Than Specified

Consider a function that computes

function y = calSecondOrderPoly(x, a, b, c)

switch nargin case 4 % do nothing case 3 c = 0; case 2 c = 0; b = 0; otherwise error('Incorrect input');end y = a*x.^2 + b*x + c;

cbxax 2

Switch according to input arguments number

Default value

Page 10: Introduction_to_Matlab_Tutorial_7.ppt

10

Matlab Functions Can Be Called With Fewer Output Arguments Than Specified

]2,[ 2 baxcbxax

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);

Page 11: Introduction_to_Matlab_Tutorial_7.ppt

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 == 2 y_derivative = 2*a*x + b;end

Checks number of output argumentsCan help avoid expensive computations when they are not necessary

Page 12: Introduction_to_Matlab_Tutorial_7.ppt

12

Example -

Write a function subtractTwoNums Input: a, b Output: a-b

Add Help to the function Try calling the function (Debugger) *Extra: if the function needs to

return two output variables: Output: [a-b, b-a]

Page 13: Introduction_to_Matlab_Tutorial_7.ppt

13

Top Down Design

A method to solve complex problems

Principles: Start from large problems to

small A function does one task Think before you code

Page 14: Introduction_to_Matlab_Tutorial_7.ppt

14

Top Down Design and Debugging – Tic-Tac-Toe Example

Problem specifications:

Build a tic-tac-toe game for two players.

Page 15: Introduction_to_Matlab_Tutorial_7.ppt

15

Lets break the problem top-down

Play Tic-Tac-Toe

Get Next Move

Get rowGet column

Check whether the move is legal

Display the game matrix

Update the game matrix

Check for a winner

Announce the winnerInitiate the

game matrix

Have somegame matrix

Page 16: Introduction_to_Matlab_Tutorial_7.ppt

16

Choosing the Data Structures

We will use two game matrices Warning: We use it here for simplicity, usually

it is better to avoid data duplication

1 NaN NaN

NaN NaN NaN

NaN 2 NaN

‘ X ‘ ‘ – ‘ ‘ – ‘

‘ – ‘ ‘ – ‘ ‘ – ‘

‘ – ‘ ‘ O ‘ ‘ – ‘

“Num_mat” - 3x3 numeric matrix

“display_mat” - 3x9 char matrix

Page 17: Introduction_to_Matlab_Tutorial_7.ppt

17

Writing the functions – “Go with the (control) flow”

Play Tic-Tac-Toe Initiate game matrix Initiate “who won flag” variable to 0 Initiate “current player flag” variable to

1 Loop 9 times (for i=1:9):

Get Next Move Update game matrix Display game matrix Check for winner – if found a winner:

Update “who won flag” (1 or 2) and Break Switch the “current player flag” 1<->2

Announce winner according to the “who won flag” variable

Get row Get column Check if it is

a legal move

“Flags” –

A variable which holds information

about the program status

and helps you control the flow

A

Page 18: Introduction_to_Matlab_Tutorial_7.ppt

Weizmann 2010 © 18

Lets look at the code of the main function:

edit playTicTacToe.m;

Notice the local functions

Page 19: Introduction_to_Matlab_Tutorial_7.ppt

19

Debugging Run Time Errors

Our weapons: Break points –

Red Gray Modifying a file

Debug buttons

Debug menu Stop if errors / warn

There are two bugs

Lets find them . .

To the code!

Page 20: Introduction_to_Matlab_Tutorial_7.ppt

20

Error Syntax errors –

Lets try to run playTicTacToe Runtime 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 valid

Debugger …

function func1()

func2()

function func2()

Try

func3();

Catch

disp(‘Caught’);

end

function func4 ()

A = ones(1,1);

B = A(1,2);

func1;

function func3()

func4()

Page 21: Introduction_to_Matlab_Tutorial_7.ppt

21

Recursion – factorial example

function res = myFactorial(x) % check: x is a non-negative

integer if (x == 0 || x == 1) res = 1;else res = x * myFactorial(x-1);end

Ah ha!

The factorial of 1 is 1!

I don’t know what is factorial of 3

But I know it is 3 multiply the factorial of 2

I don’t know what is factorial of 2

But I know it is 2 multiply the factorial of 1

Page 22: Introduction_to_Matlab_Tutorial_7.ppt

22

Summary Introduction Functions M file structure Functions workspace Functions Input and output Top down design Local functions Debugger Recursion More:

Functions and commands Functions and the matlab search path