Upload
jocelyn-chapman
View
216
Download
0
Embed Size (px)
Citation preview
FunctionsFunctions
CS 103CS 103
March 3, 2004March 3, 2004
ReviewReview
A function is a set of code we can execute A function is a set of code we can execute on command to perform a specific taskon command to perform a specific task
When we call a function, we can pass When we call a function, we can pass arguments (variables) to and from the arguments (variables) to and from the functionfunction
By default, variables in Matlab are local in By default, variables in Matlab are local in scopescope
Polling QuestionPolling Question
Given the following code, what is the value Given the following code, what is the value of x after the main program has run?of x after the main program has run?
MAIN PROGRAM
x = 5;
y = test_function(x)
function [a] = test_function(b)
x = 10
a = x* b
x = 2
b = 4
y = 1
Scope & Local VariablesScope & Local Variables The scope of a variable defines what parts of a The scope of a variable defines what parts of a
program can access itprogram can access it
By default, all variables in Matlab are local in By default, all variables in Matlab are local in scopescope
Local scope means:Local scope means: Only the function or main program that created the Only the function or main program that created the
variable can read or modify that variable. To the rest variable can read or modify that variable. To the rest of Matlab, it’s like that variable doesn’t existof Matlab, it’s like that variable doesn’t exist
Local variables created by functions are deleted after Local variables created by functions are deleted after the function endsthe function ends
Local ScopeLocal Scope% Main Program
A = 13
B = my_function(A)
% The Function
Function [B] = my_function(A)
B = sqrt(A);
AA AA BB
BB
Computer’s Memory
Arguments in a function can have the same name as those in the main program (or another function)….but they’re NOT the same variable.
Calling & Defining FunctionsCalling & Defining Functions The syntax for calling and defining functions takes one of four forms The syntax for calling and defining functions takes one of four forms
depending on whether there are input or output argumentsdepending on whether there are input or output arguments
Calling a function: Calling a function: [outputs]=function_name(inputs)[outputs]=function_name(inputs)[outputs]=function_name[outputs]=function_namefunction_name(inputs)function_name(inputs)function_namefunction_name
Defining a function: Defining a function: function [outputs]=function_name(inputs)function [outputs]=function_name(inputs)function [outputs]=function_namefunction [outputs]=function_namefunction function_name(inputs)function function_name(inputs)function function_namefunction function_name
Polling QuestionPolling Question
Write a function called safe_inverse()Write a function called safe_inverse()
This function will have one input argument This function will have one input argument and one output argumentand one output argument
If the function were called y=safe_inverse(x) If the function were called y=safe_inverse(x) then the function should returnthen the function should returny = 1/x unless x = 0, in which case y = 0y = 1/x unless x = 0, in which case y = 0
Passing ArgumentsPassing Arguments
You don’t always have to pass the You don’t always have to pass the arguments you define!arguments you define!
A function can be called with fewer A function can be called with fewer arguments, but not with more arguments arguments, but not with more arguments than specifiedthan specified
Handling Variable ArgumentsHandling Variable Arguments
Matlab has a series of functions that can check Matlab has a series of functions that can check what types of arguments are being passedwhat types of arguments are being passed narginnargin = number of input arguments = number of input arguments nargoutnargout = number of output arguments = number of output arguments nargchk(min,max,nargin)nargchk(min,max,nargin) can check for too few can check for too few
arguments, but not for too manyarguments, but not for too many
After using these functions to determine how After using these functions to determine how many arguments have been passed, you have to many arguments have been passed, you have to write the code to handle the various possibilitieswrite the code to handle the various possibilities
Example Problem:Example Problem:Finding Prime NumbersFinding Prime Numbers
We wish to find a series of prime numbersWe wish to find a series of prime numbers
Algorithm: Sieve of Eratosthenes Algorithm: Sieve of Eratosthenes (ca 240 BC)(ca 240 BC)
Method:Method: List the numbers from 1 to NList the numbers from 1 to N Starting with 2, strike every multiple of 2 from the listStarting with 2, strike every multiple of 2 from the list Then strike the multiples of 3Then strike the multiples of 3 Then 4, 5, 6, etc. all the way up to NThen 4, 5, 6, etc. all the way up to N The remaining list are prime numbersThe remaining list are prime numbers
Creating a Primes FunctionCreating a Primes Function
Now, suppose we want to alter our script to Now, suppose we want to alter our script to make it a functionmake it a function
This function should allow us to find the prime This function should allow us to find the prime numbers from 1 to N if the user gives us an N, or numbers from 1 to N if the user gives us an N, or from M to N if the user gives us bothfrom M to N if the user gives us both
The function should return a list of prime The function should return a list of prime numbers and, if requested, the average of those numbers and, if requested, the average of those prime numbersprime numbers
Creating a Primes FunctionCreating a Primes Function
What does the function need to do What does the function need to do differently?differently?We need to figure out how many input We need to figure out how many input
arguments were passedarguments were passedIf 1, calculate primes from 1 to NIf 1, calculate primes from 1 to NIf 2, calculate primes from M to NIf 2, calculate primes from M to N
How many output arguments were requested?How many output arguments were requested?By default, we will always return the list of primesBy default, we will always return the list of primesIf 2, calculate the averageIf 2, calculate the average
Using narginUsing nargin
We can use nargin to determine the We can use nargin to determine the number of input argumentsnumber of input arguments
Note that arguments are always passed in Note that arguments are always passed in order!order!
ourprimes(10, 250) ourprimes(100)
Function [list_of_primes, avg]=our_primes(M, N)
Dynamic PolymorphismDynamic Polymorphism
A function where the output is determined A function where the output is determined during the running of the function by the during the running of the function by the type of the input argumentstype of the input arguments
Sometimes just the value is different, and Sometimes just the value is different, and sometimes the shape or type is differentsometimes the shape or type is different
Global VariablesGlobal Variables Variables which can be used by all of Matlab, Variables which can be used by all of Matlab,
including user-defined functionsincluding user-defined functions
Syntax:Syntax: global variable_name global variable_name
The global declaration should be placed in your The global declaration should be placed in your main program and functions that will use itmain program and functions that will use it
Global variables should not be used as Global variables should not be used as arguments passed to a functionarguments passed to a function
Global ScopeGlobal Scope% Main Program
global x
X = 15;
A = 13
B = my_function(A)
% The Function
Function [B] = my_function(A)
global x
B = sqrt(A);
x = 10;
AA AA BB
BB XX
Computer’s Memory
Arguments in a function can have the same name as those in the main program (or another function)….but they’re NOT the same variable unless defined as GLOBAL