12.3. Return values#
The majority of functions output (or return) an object or a tuple of multiple objects. To return something from a function we use declare an output variable.
function output = function_name(argument1, argument2, ...)
% commands
end
To demonstrate this enter the following code into the end of your program
% ------------------------------------------------------------------------
function y = double(x)
y = 2 * x;
end
and make a call to this function by entering the following code before the function declarations.
% Return values
double(3)
double(5)
Run your program and you should see the following added to the command window.
ans =
6
ans =
10
12.3.1. Multiple return values#
We can return multiple values from a function by listing the output varaibles in an array.
function [output1, output2, ...] = function_name(argument1, argument2, ...)
% commands
end
To demonstrate this lets write a function calculates the volume and surface area of a cylinder. Enter the following code into your program.
% ------------------------------------------------------------------------
function [volume, surface_area] = cylinder(radius, height)
volume = height * pi * radius ^ 2;
surface_area = height * 2 * pi * radius;
end
and make a call to this function by entering the following code before the function declarations.
% Multiple return values
[vol, area] = cylinder(1, 2);
fprintf("Volume : %8.4f \n", vol)
fprintf("Surface area : %8.4f \n", area)
Run your program and you should see the following added to the command window.
Volume : 6.2832
Surface area : 12.5664
12.3.2. Exercises#
Write a function called my_norm()
that calculates the norm (magnitude) of a vector of unknown length. Use your function to calculate
\(\|(1, 2, 3)\|\)
\(\|(4, 5, 6, 7)\|\)
Euclid’s algorithm for computing the greatest common divisor (GCD) of two numbers \(x\) and \(y\) is
Find the remainder \(r\) of \({x}\div{y}\)
Set \(x = y\) and \(y = r\)
Repeat steps 1 and 2 until \(y = 0\) then the GCD is \(x\)
Write a function called my_gcd()
that returns the GCD of two numbers. Use your function to calculate the GCD of:
14 and 245
2414 and 54145
The following sequence converges to the square root of a positive number \(x\)
where \(x_0 = 0\) and \(x_1 = 1\). Define a function called my_sqrt()
that calculates numbers in this sequence until the difference two successive numbers is less that \(5 \times 10^{-5}\). Use your function to calculate
\(\sqrt{144}\)
\(\sqrt{12345}\)