Skip to main content
Logo image

Subsection Functions

A MATLAB function is a .m file that stores a sequence of MATLAB commands. Like a script, MATLAB executes those commands from top to bottom. The key difference is that a function is designed to accept inputs (known information) and return outputs (desired information).
You have already used many built-in MATLAB functions (such as sqrt, abs, and floor). The functions you write in this course work the same way: MATLAB only cares about the inputs you provide and the outputs the function returns.

One Input, One Output.

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.

Two Inputs, One Output.

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.
Listing 17. MATLAB Function with 2 Inputs and 1 Output
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.

Two Inputs, Two Outputs.

Functions can return multiple outputs. To specify multiple outputs, list them in square brackets in the function header. Here is an example of a function that computes both the perimeter and area of a rectangle given the lengths of its two sides.
Listing 18. MATLAB Function with 2 Inputs and 2 Outputs
function [perimeter, area] = rectangle_properties(side1, side2)

	% Use the inputs (side1 and side2) 
	% to compute the outputs (perimeter and area)
	perimeter = 2 * side1 + 2 * side2;
	area = side1 * side2;

end
To call this function and capture both outputs, use square brackets on the left side of the assignment. For example, to compute the perimeter and area of a rectangle with side lengths 4 and 7, type:
[p, a] = rectangle_perimeter(4, 7)	% returns p = 22 and a = 28
MATLAB will run the commands inside the function, using the input values you provided (4 and 7) to compute the output values (22 and 28). The results are then returned to the Command Window and stored in the variables p and a.

πŸ“: Ignoring Outputs.

πŸ§‘πŸ»β€πŸ’» Class Activities πŸ§‘πŸ»β€πŸ’» Class Activities

1. Hello Function.

(a)
Create a function named hello with no inputs and outputs that displays 'Hello World' using the fprintf command. Test your function by typing hello in the command window.
Solution.
function hello()

	fprintf('Hello World!\n');

end
(b)
Modify the function to accept one input (name) and display a greeting, such as 'Hello Alice, nice to meet you!' where name is 'Alice'.
Solution.
function hello(name)

	fprintf('Hello %s, nice to meet you!\n', name);

end
(c)
Try typing hello with no input and run it. What error message do you get, and what is MATLAB telling you to fix?
Solution.
The error message is:
Not enough input arguments.

Error in hello (line 3)
	fprintf('Hello %s, nice to meet you!\n', name);
This means that the function hello expects one input argument, but none was provided when it was called.
(d)
Now, test your function with an input: hello('Robyn').
Solution.
When you run hello('Robyn'), the output is:
Hello Robyn, nice to meet you!

2. Projectile Height Function.

Package the projectile height model script as a function.
(a)
Create a function named projectile_height that takes four inputs: initial height h0, initial velocity v0, gravity g, and time t.
The function should return one output, the height h at time t, given by:
\begin{equation*} h(t) = h_0 + v_0 t - \frac{1}{2} g t^2\text{.} \end{equation*}
Do not include any fprintf commands inside the function. The function’s body should contain only a single line that computes the height.
Solution.
function h = projectile_height(h0, v0, g, t)

	h = h0 + v0*t - 0.5*g*t^2;

end
(b)
Test your function using h0 = 1.5, v0 = 12, g = 9.81, and t = 0.8.
Solution.
h = projectile_height(1.5, 12, 9.81, 0.8);
fprintf('h = %.2f m\n', h);
The computed height is h = 7.96 meters.

3. Circle Metrics Function.

Write a function that returns more than one output.
(a)
Create a function named circle_metrics that takes one input r (radius) and returns two outputs: C (circumference) and A (area).
Solution.
function [C, A] = circle_metrics(r)

	C = 2*pi*r;
	A = pi*r^2;

end
(b)
Test your function with r = 4.5 and print the results with three decimal places.
Solution.
[C, A] = circle_metrics(4.5);
fprintf('C = %.3f\t A = %.3f\n', C, A);

4. Coin Total Function.

In the piggy bank script, you computed a total value from the number of pennies, nickels, dimes, and quarters. Now, package that computation into a function so you can reuse it with different coin counts.
(a)
Create a function named coin_total with four inputs: nPennies, nNickels, nDimes, and nQuarters. The function should return one output, totalDollars.
Solution.
function totalDollars = ...
	coin_total(nPennies, nNickels, nDimes, nQuarters)

	% Compute total value in cents
	cents = nPennies + 5*nNickels + 10*nDimes + 25*nQuarters;
	totalDollars = cents/100;
end
(b)
Test your function by running the following command in the Command Window.
total = coin_total(1, 1, 1, 1)
Solution.
Your result should be a single dollar amount stored in total.
(c)
In the Command Window, compute dollars and leftover cents from total (do not change the function).
Solution.
nDollars = floor(total);
nCents = total - 100 * nDollars;
fprintf('Total value: $%i.%02i\n', nDollars, nCents);

5. Quadratic Solver Function.

Write a function that computes the two solutions of \(a x^2 + b x + c = 0\) using the quadratic formula. This function may return complex solutions when the discriminant is negative.
(a)
Create a function named quadratic with inputs a, b, and c. Return two outputs, x1 and x2.
Solution.
function [x1, x2] = quadratic(a, b, c)

	discriminant = b^2 - 4*a*c;
	x1 = (-b + sqrt(discriminant)) / (2*a);
	x2 = (-b - sqrt(discriminant)) / (2*a);

end
(b)
Test your function on each equation below, and print the results. Use the real-and-imaginary printing approach so your output also works for complex solutions.
  1. \(\displaystyle 2x^2 - 7x + 5 = 0\)
  2. \(\displaystyle 15x^2 - 135x + 300 = 0\)
  3. \(\displaystyle x^2 + 36 = 0\)
Solution.
[x1, x2] = quadratic(2, -7, 5);
fprintf('Eqn 1: x1 = %g%+gi, x2 = %g%+gi\n', real(x1), imag(x1), real(x2), imag(x2));

[x1, x2] = quadratic(15, -135, 300);
fprintf('Eqn 2: x1 = %g%+gi, x2 = %g%+gi\n', real(x1), imag(x1), real(x2), imag(x2));

[x1, x2] = quadratic(1, 0, 36);
fprintf('Eqn 3: x1 = %g%+gi, x2 = %g%+gi\n', real(x1), imag(x1), real(x2), imag(x2));
(c)
Are there any inputs for which this function fails? Give an example and explain why.
Solution.
The function fails when a = 0, because the quadratic formula divides by \(2a\text{.}\) Handling a = 0 properly requires making a decision inside the function, which needs flow control.

Exercises πŸ€”πŸ’­ Conceptual Questions

1. Function Concepts.

(a) Purpose of a Function.
A MATLAB function is most useful when you want to:
  • clear the Command Window automatically
  • store a long list of comments
  • create a reusable tool that takes inputs and returns outputs
  • avoid using variables
(b) File Name Match.
    If a function is named coin_total, then its file should be saved as coin_total.m.
  • True.

  • Matching the file name to the function name prevents β€œfunction not found” and naming errors.
  • False.

  • Matching the file name to the function name prevents β€œfunction not found” and naming errors.
(c) Function Workspace.
    Variables created inside a function automatically appear in the Workspace after the function finishes.
  • True.

  • A function uses its own workspace, so its internal variables do not automatically become Workspace variables.
  • False.

  • A function uses its own workspace, so its internal variables do not automatically become Workspace variables.
(d) Calling a Function.
Which of the following is a function call with three inputs?
  • f = 2, 3, 4
  • f(2; 3; 4)
  • f(2, 3, 4)
  • f = (2, 3, 4)
(e) Multiple Outputs.
To store two outputs from a function, you should write:
  • a, b = f(x)
  • (a, b) = f(x)
  • [a, b] = f(x)
  • a = f(x), b
(f) Function Header Meaning.
In the header function y = f(x), which symbol represents the output?
  • f
  • x
  • y
  • function
(g) Calling Functions from Scripts.
    A script can call a function that you wrote (for example, coin_total), as long as the function file is available in the Current Folder (or on the path).
  • True.

  • This is one of the main benefits of functions: they simplify scripts by packaging common computations.
  • False.

  • This is one of the main benefits of functions: they simplify scripts by packaging common computations.
(h) Matching the Description.