Sie sind auf Seite 1von 27

Function

week 6

By Ji Hui
Department of Mathematics
Repeating data processing by calling 
the same code

• Script
– a script is a type of file with commend lines  which 
you can call from the commend windows or from 
some other script
– File with an extension of .m
– Function names must follow the MATLAB rules for 
variable names.
Example
• Problem
– Given some positive integer x, find its factorial
• Script file: myprime.m
• Code inside file
x = 209;
isprime=1;
for k=2:x‐1
r= x/k;
if(round(r)==r),  isprime=0;  break; end
end 
More friendly and structured re‐usable 
code

• Function
– A function is a type of script file (i.e. a file with an 
extension of .m) which you can ‘call’ interactively, or 
from some script.
– A function M‐file communicates with the MATLAB 
workspace only through specially designated input 
and output arguments.
– Functions are indispensable when it comes to 
breaking a problem down into manageable logical 
pieces. (discussed in later lectures)
General form of a function
A function M‐file name.m has the following 
general form:
• function [ outarg1, outarg2, … ] = name( 
inarg1, inarg2, … )
• ...
• outarg1 = ... ;
• Outarg2= … ;
• …
An example of function
• file: myprime.m
• Code inside file
function y=myprime(x)
y=1;
for k=2:x‐1
r= x/k;
if(round(r)==r),  y=0;  break; end
end 
More on rules of function
• Keyword function
– The function file must start with the keyword 
function
• Input and output arguments.
– The input and output arguments (inarg1, outarg1, 
etc.) are “dummy” variables, and serve only to 
define the function’s means of communication 
with the workspace.
(cont’)
• Multiple output arguments
– If there is more than one output argument, the output 
arguments must be separated by commas and 
enclosed in square brackets in the function definition 
line, as shown.
• Naming convention for functions
– Function names must follow the MATLAB rules for 
variable names.
– If the filename and the name defined in function 
definition line are different, the internal name is 
ignored
(cont’)
• Local variables: scope
– Any variables defined inside a function are 
inaccessible outside the function.
– they exist only inside the function, which has its 
own workspace separate from the base 
workspace of variables defined in the Command 
Window.
Example of local variable
• For example,  if you use a variable as a loop 
index, say, inside a function, it will not clash with 
a variable of the same name in the workspace or 
in another function.
>> y=myprime(10)
y =
0
>>k
??? Undefined function or variable 'k'.
How to access variable inside 
functions
• Define the variable as one of out‐argument
• Code of myprime.m
function [y,factor]=myprime(x)
factor=1;
y=1;
for k=2:x‐1
r= x/k;
if(round(r)==r),  
y=0; 
factor=k;
break; end;
end;
How function arguments are passed
• input arguments appear to be passed by value.
– If a function changes the value of any of its input 
arguments, the change is not reflected in the actual 
input argument on return to the workspace
• Sample code
function y=myprime(x)
y=1;
for k=2:x‐1
r= x/k;  if(round(r)==r),  y=0;  break; end;
end;
x=x^2;
(cont’)
• Results
>>x=10;
>>y=myprime(x);
>>x
x  =
10
• It is the same as 
>>y=myprime(10);
• Thus, a function may be called with the same input and 
output argument
>> [x,factor]=myprime(x);
How to call a function
• You should use the number of input arguments 
exactly the same as the function defines.
– Actually, in Matlab,  variable length of input argument 
list is allowed by using advanced programming 
structure, we leave it in this course
• If you call a function with no output arguments, 
the value of the first one in the definition is 
returned.
• If you call a function with fewer number of 
output argument, the value of the first few 
number of output arguments will be returned.
subfunction
• A function M‐file may contain the code for 
more than one function
– the first function in a file is the primary function
– Additional functions in the file are called 
subfunctions, and are visible only to the primary 
function and to other subfunctions in the same 
file
Function name resolution
• Remember that a variable in the workspace 
can ‘hide’ a built‐in function of the same 
name, and a built‐in function can hide an M‐
file.
• when MATLAB encounters a name 
– It always tries to use a name as a variable first, 
before trying to use it as a script or function.
(con’t)
• When you type a name at the command‐line 
prompt, say goo, the MATLAB interpreter goes 
through the following steps:
1. Looks for goo as a variable.
2. Looks in the current directory for a script file called 
goo.m.
>>pwd
1. Looks for goo as a built‐in function, like sin or pi.
2. Looks (in order) in the directories specified by 
MATLAB’s search path for a script file called goo.m. 
Use File ‐> Set Path to view and change MATLAB’s
Recursive function
• Many (mathematical) functions are defined 
recursively,
• Example: calculating the factorial

n!=      
• Matlab allows functions to call itself.                    
Example code
• File: myfactorial.m
function y =myfactorial(n)
if n > 1
y = n * fact(n‐1);
else
y = 1;
end;
More on recursive function
• Recursive functions are usually written in this 
way: an if statement handles the general 
recursive definition; the else part handles the 
special case (n=1).
• Although recursion appears deceptively 
simple, it is an advanced topic, use it 
cautiously in practice.
Help text for function
• Help is one essential part of programming, 
equally important as the running code
• Comment using %
– % symbol is a flag that indicates all information to 
the right is not part of the command. It is a 
comment.
– For example
>> x=sqrt(5) % find the square root of 2
(con’t)
• When you type help function_name, MATLAB displays the 
comment lines that appear between the function definition 
line and the first non‐comment
• File: myfactorial.m
function y =myfactorial(n)
% Calcuating the factorial of given positive integer
if n > 1
y = n * fact(n‐1);
else
y = 1;
end;
• Results:
>> help myfactorial
Data input and output
• In scientific  computing, besides interactively 
solving problems in workspace. You may wish 
to import data to be operated on 
mathematically, and export data for future 
use.
– the importing of data into the MATLAB workspace 
from various sources
– the exporting of data to files in your work 
directory for later use with MATLAB or with other 
software tools.
Type of data file
• ASCII text data
– Readable as text
– Need more space
• Binary data
– Proprietary format for specific programming 
– Unreadable by other program
– Need less space
Ascii data file by load and save
• Exporting text (ASCII) data
– For example, store a vector A to a text file myData.txt
>> A=[1.30, 240, 20.20, 30,1];
>>save myData.txt A –ascii
Open file myData.txt using notepad 
• Import text (ASCII) data
>> A = load(’myData.txt’)
• Data imported in this way doesn’t have to be 
created by MATLAB. You can create it in a text 
editor,  or by other programs
Binary data file
• Exporting binary data
>> save filename x y z
– saves the variables x, y and z in the file 
filename.mat in MATLAB proprietary binary 
format
– Only accessible by MATLAB
– If no variables are listed the entire workspace is 
saved.
– The extension .mat is the default—you can 
specify a different extension
(con’t)
– .mat files from different versions of matlab maybe 
are not compatible to each other.
• Importing binary data
>> load filename
– loads all the variables from filename.mat into the 
workspace
• Low‐level file I/O functions (will be discussed 
in future lectures)

Das könnte Ihnen auch gefallen