Skip to main content
Logo image

Subsection Programming with Functions

Functions help you package a useful calculation into a reusable tool. Instead of rewriting the same computations in many scripts, you write them once as a function and then call that function whenever you need it.
Here is an example of a simple function that computes the perimeter of a square given its side length.
Listing 16. MATLAB Function with 1 Input and 1 Output
function perimeter = square_perimeter(side)

	% Use the input (side) to compute the output (perimeter)
	perimeter = 4 * side;

end
To use this function, save it in a file named square_perimeter.m. Then, in the Command Window (or in another script), call the function by providing an input value inside parentheses. For example, to compute the perimeter of a square with side length 5, type:
p = square_perimeter(5)	% returns 20 and stores it in variable p
MATLAB will run the commands inside the function, using the input value you provided (5) to compute the output value (20). The result is then returned to the Command Window and stored in the variable p.