Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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:
Weizmann 2010
Goals
Introduction
Functions M file structure
Functions workspace
Functions Input and output
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.
90
95 100 98
88
92
91.85
643
100
4
Output
function
Input
my_sum=a+b;
The input
variables
6
help:
Functions
Documentation and
Variable Verification First line
Usage
Input
Output
Examples
Testing for
proper
variables
functionmy_sum=sumTwoNums(a,b)
%SUMTWONUMSsumtoscalars
%thisfunctionsumstwoscalar
%andreturnstheresult
%INPUT:
%athefirstscalar
%bthesecondscalar
%
%OUTPUT:
%my_sumthesumofaandb;sum=a+b
if(~isscalar(a))
error('Firstargumentisnotascalar');
end
if(~isscalar(b))
error('Secondargumentisnotascalar');
end
Each Instance of A
Function Run Has Its
Assume we
wrote the
function:
Own
Workspace
functionmy_sum=sumTwoNums(a,b)
my_sum=a+b;
Matlab
Workspace:
a=1
b=2
X=3
Function
Workspace:
a=3
b=4
my_sum =
7
y=4
s=7
8
ax bx c
2
functiony=calSecondOrderPoly(x,a,b,c)
switchnargin
case4
%donothing
case3
Default
c=0;
case2
value
c=0;
b=0;
otherwise
error('Incorrectinput');
end
y=a*x.^2+b*x+c;
Switch
according to
input arguments
number
Recall:
[y,y_derivative]=calSecondOrderPoly(x,a,b,c);
[ax 2 bx c,2ax b]
10
y=a*x.^2+b*x+c;
Checks number
of output
ifnargout==2
arguments
Can help avoid
y_derivative=2*a*x+b;
expensive
end
computations when
they are not necessary
11
Example
Input: a, b
Output: a-b
13
Problem
specifications:
Build a tic-tac-toe
game for two players.
14
Get column
Get row
Check whether
the move is legal
Display the
game matrix
15
NaN
NaN
NaN
NaN
NaN
NaN
NaN
16
Flags
A variable which
holds information
about the
program status
and helps you
control the flow
Get row
Get column
Check if it is
a legal move
17
Weizmann 2010
18
Our weapons:
Break points
Red
Gray
Modifying a file
Debug buttons
Debug menu
Stop if errors / warn
To the code!
19
func1;
Error
Syntax errors
functionfunc1()
func2()
functionfunc2()
Try
Runtime errors
func3();
Catch
disp(Caught);
end
functionfunc3()
func4()
functionfunc4()
A=ones(1,1);
B=A(1,2);
20
Recursion factorial
example
functionres=myFactorial(x)
%check:xisanonnegativeinteger
if(x==0||x==1)
res=1;
else
res=x*myFactorial(x1);
end
Ah ha!
The factorial of 1 is 1!
21
Summary
Introduction
Functions M file structure
Functions workspace
Functions Input and output