Sie sind auf Seite 1von 21

Eilon Sharon, Weizmann 2008

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

Download:

(http://www.weizmann.ac.il/feinberg/courses/EranEden/course_outline.htm)

From the course website

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

Tutorial 7:
Functions and Program Design

Introduction to Matlab
& Data Analysis

Functions and commands


Functions and the matlab search path

Local functions
Debugger
Recursion
More:

Top down design

Introduction
Functions M file structure
Functions workspace
Functions Input and output

Goals

One M-file, One Task, One Workspace

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.

Function Is an Independent Piece


of Code Which Performs a Task

90

95

100

98

88

92

91.85

Output:
(Data)

643

100
4

y = mean(x) y = sum(x) y = max(x)

X = 80
Functions:

Input (Object / Data):

Variables The Data Objects,


Functions Are The Actions

function

Input

It hides the code and the its workspace


and communicate with the world using
the input and output variables

A function is a black box

Output

A Function Is a Black Box

5
5

(else - Matlab will give an error)

Assign the output variables

my_sum = a+b;

The input variables

function my_sum = sumTwoNums(a,b)

sumTwoNums.m:

Should be same as the name of the file

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

The file is a Matlab function

Functions M file structure

Testing for
proper
variables

Examples

Output

Input

Usage

help:

my_sum = a+b;

Calculations and Output assignment

if (~isscalar(a))
error('First argument is not a scalar');
end
if (~isscalar(a))
error('Second argument is not a scalar');
end

function my_sum = sumTwoNums(a,b)


First line
% SUMTWONUMS sum to scalars
% this function sums two scalar
% and returns the result
H1 line, (lookfor)
% INPUT:
% a - the first scalar
% b - the second scalar
%
% OUTPUT:
% my_sum - the sum of a and b; sum = a+b

Functions Documentation
and Variable Verification

=
=
=
=
=

1;
2;
3;
4;
sumTwoNums(x, y)

What is the output?


s = 7

a
b
x
y
s

In the workspace we run:

s=7

y=4

X=3

b=2

a=1

Workspace:

Matlab

Assume we wrote the function:


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

 my_sum = 7

b=4

a=3

Function
Workspace:

Each Instance of A Function


Run Has Its Own Workspace

ax + bx + c

y = a*x.^2 + b*x + c;

Switch according
to input arguments
number

= calSecondOrderPoly(x, a, b, c)

switch nargin
case 4
% do nothing
case 3
Default value
c = 0;
case 2
c = 0;
b = 0;
otherwise
error('Incorrect input');
end

function y

Consider a function that computes

Matlab Functions Can Be Called With


Fewer Input Arguments Than Specified

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:

[r,c] = find(A) , ind = find(A);

Recall:

[ax 2 + bx + c,2ax + b]
10

[y, y_derivative] = calSecondOrderPoly(x, a, b, c);

Matlab Functions Can Be Called With


Fewer Output Arguments Than Specified

if nargout == 2
y_derivative = 2*a*x + b;
end

y = a*x.^2 + b*x + c;

Can help avoid expensive


computations when they
are not necessary

Checks number of
output arguments

11

function [y, y_derivative] = calSecondOrderPoly(x, a, b, c)

Matlab Functions Can Be Called With


Fewer Output Arguments Than Specified

Start from large problems to small


A function does one task
Think before you code

A method to solve complex


problems
Principles:

Top Down Design

12

Build a tic-tac-toe game


for two players.

Problem specifications:

Top Down Design and Debugging


Tic-Tac-Toe Example

13

Display the
game matrix

Update the
game matrix

Initiate the
game matrix

Have some
game matrix
Get row

Check whether
the move is legal

Get column

Get Next Move

Play Tic-Tac-Toe

14

Announce the winner

Check for a winner

Lets Break the Problem Top-Down

NaN
NaN
2

NaN

NaN

NaN

NaN

NaN

15

display_mat - 3x9 char matrix

Warning: We use it here for simplicity, usually it is


better to avoid data duplication

We will use two game matrices

Num_mat - 3x3 numeric matrix

Choosing the Data Structures

Update who won flag (1 or 2) and Break

Switch the current player flag 1<->2

Get Next Move


Update game matrix
Display game matrix
Check for winner if found a winner:

Announce the winner according to the


who won flag variable (0 = draw)

Initate game matrix


Initiate who won flag variable to 0
Initiate current player flag variable to 1
Loop 9 times (for i=1:9):

Play Tic-Tac-Toe

16

Get row
Get column
Check if it is
a legal move

and helps you


control the flow

about the
program status

A variable which
holds information

Flags

Writing the Functions


Go With the (Control) Flow

Eilon Sharon, Weizmann 2008

Notice the local functions

edit playTicTacToe.m;

17

Lets look at the code of the main function:

Red
Gray
Modifying a file

Debug menu
Stop if errors / warn

Debug buttons

Our weapons:
 Break points

To the code!

Lets find them . .

There are bugs

Debugging Run Time Errors

18

Lets try to run playTicTacToe

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

Runtime errors

Syntax errors

Error

end

disp(Caught);

func3();

B = A(1,2);

A = ones(1,1);

func4 ()

func4()

func3()

Catch

Try

func2()

func2()

func1()

func1;

19

The factorial of 1 is 1!

Ah ha!

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

% check if x is a non-negative integer

function res = myFactorial(x)

20

But I know it is 2 multiply


the factorial of 1

I dont know what is


factorial of 2

But I know it is 3 multiply


the factorial of 2

I dont know what is


factorial of 3

Recursion factorial example

Functions and commands


Functions and the matlab search path

Local functions
Debugger
Recursion
More:

Top down design

Introduction
Functions M file structure
Functions workspace
Functions Input and output

Summary

21

Das könnte Ihnen auch gefallen