Академический Документы
Профессиональный Документы
Культура Документы
Functions are perhaps the most important tool for programming. They allow the programmer to
define a specific action that (usually) takes in some data, does some processing, and returns a
result, much like most math functions. Yet, no matter what the purpose of a function is, the
"syntax" for defining and using a function is always the same. Here we discuss how to use and
define functions in Matlab.
Make sure you review the Topic on Commenting and Style to go along with this Design Pattern
% CODE
end % function
end % function
%
% Header Comment
%
he function prototype is a means for telling Matlab that the M file contains a function (not a
script) and what the name of the function is, what its return variable is called, and what
parameters it takes. When the function is called (run by the computer), the computer starts at the
first line of code following the prototype.
In the average function above, the first actual line of the function is:
parameters ZERO or more variables for which data is COPIED into the function.
end The key word end, specifying the end of the functions code
3. parameters - symbolic names for the inputs to the function (the data the function will
process to compute an answer.
In the case above, the parameters are named "first_value" and "second_value"
1. Calculation - Code to compute a value. In the above case the average value of the two
input parameters is computed.
2. Output/Result variable - This is the symbolic name for the variable which will contain the
result of all the work of the function. In the above case, the result variable is "avg".
Whatever value is in the variable "avg" when the function ends, is "returned" to the
caller of the function.
Functions should (almost) never contain the fprintf command. If you want to print the
output of a function, then you should:
3. Example
grade(1) = 87;
grade(2) = 95;
>> x = 20;
>> y = 10;
>> z = average(x,y);
>> z = average(200,100);
>> z = average(x,12);
>> w = average(average(5,10), x);
CODE
end % function
CODE
CODE
With No Parameters
Sometimes a function will just "do an action" but not based on anything the user wants. Such a
function would be said to be "hard coded" and do the same thing every time. For example, the
random function in most languages will return a random number but does not require any actual
parameters to make it work.
CODE
end %end of function