Subsection Writing Functions
To create a function in MATLAB, you start by opening a new function file. Here is an example of a function that computes the perimeter of a rectangle given its two sides.
function perimeter = rectangle_perimeter(side1, side2)
% Use the inputs (side1 and side2)
% to compute the output (perimeter)
perimeter = 2 * side1 + 2 * side2;
end
The first line of the function file is the function header, which defines the functionβs name, inputs, and outputs. For example, in the function above, the line
function perimeter = rectangle_perimeter(side1, side2)
declares a function named
rectangle_perimeter that takes two inputs (side1 and side2) and returns one output (perimeter).
When you save the function, the function name should match the file name (without the
.m extension). In this example, the function is named rectangle_perimeter, so the file should be saved as rectangle_perimeter.m.
π: Where to save your function file.
Inside the function, you can use the input variables to perform calculations and assign values to the output variable. When the function is called, MATLAB executes the commands in the function file and returns the output value. Unlike scripts, intermediate variables stay inside the function unless you return them.
To call this function, provide two input values inside parentheses. For example, to compute the perimeter of a rectangle with side lengths 4 and 7, type:
p = rectangle_perimeter(4, 7) % returns 22 & stores it in p
MATLAB will run the commands inside the function, using the input values you provided (
4 and 7) to compute the output value (22). The result is then returned to the Command Window and stored in the variable p.
