Вы находитесь на странице: 1из 5

Functions in Matlab

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.

Function Design Pattern


A function in Matlab is always written using the same (starting) syntax. This syntax can be
captured in a "Design Pattern". Your job is to learn this pattern for future use (and tests). When
learning, you can refer here for help.

Make sure you review the Topic on Commenting and Style to go along with this Design Pattern

The Basic Design Pattern


Remember, as always, design patterns show you a "template" of the syntax/rules necessary to
complete a generic goal. In this case, the basic format of any Matlab function file is described.

function return_value = name_of_function( parameters )

return_value = 0; % or other default value

% CODE

end % function

A Very Simple Function File


Here is an example of a function that computes the average of two numbers. It shows the use of a
return value, two parameters, comments, and computation. This function would be saved with
the name "average.m".

function avg = average(first_value, second_value)

avg = (first_value + second_value) / 2.0;

end % function

The function Prototype or Declaration.


The very first thing you see in every function file (after the comments) is the line with the
keyword function on it. This line is called the function "prototype" or "declaration".

%
% Header Comment
%

function avg = average(first_value, second_value) % Prototype / Declaration

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:

avg = (first_value + second_value) / 2.0;

function keyword function

Optional: the name of a variable who's value is returned from function


return_value With multiple return values, we put the return value names in side square brackets. (e.g.,
function [name, date, address] = ask_for_personal_info())

= The equals sign. Required with a return variable (see above)

The name of the function (hopefully descriptive)


name
for example sin, or tan, or length...

'(' Open parenthesis

parameters ZERO or more variables for which data is COPIED into the function.

')' Closing parenthesis

CODE The code specific to the function

end The key word end, specifying the end of the functions code

Parts of the Function Design Pattern

Again, a function declaration is always of the form:


function result = name(parameters)

1. function - the key word function starts every function declaration.


2. name - a symbolic name telling the user of the function the purpose of the function. In the
case above, the name is average.

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"

Inside the function are computations and an assignment of the result(s).

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.

3. Do Not Print Inside a Function.

Functions should (almost) never contain the fprintf command. If you want to print the
output of a function, then you should:

1. Call the function and assign the value to a variable.


2. Call the print the value of the variable.

3. Example

grade(1) = 87;
grade(2) = 95;

average_grade = average( grade(1), grade(2) );

fprintf('the average of the grades %f and %f is %f'\n', ...


grade(1), grade(2), average_grade);

Examples of how to "Call" a function (from the command line):

>> x = 20;
>> y = 10;
>> z = average(x,y);
>> z = average(200,100);
>> z = average(x,12);
>> w = average(average(5,10), x);

Zero or more Return Values and Parameters:


The following examples show several variations on functions, including those that return a single
value, return no values, return many values, take parameters, take no parameters, etc.

With a Single Return Value

function return_value = name( parameters )

CODE

end % function

Without a Return Value

function name( parameters )

CODE

end % end of function

With MULTIPLE Return Values

function [value_1, value_2, value_3] = name( parameters )

CODE

end % end of function

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.

function result = name()

CODE
end %end of function

Вам также может понравиться