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#

Exercise 12.5

Write a function called my_norm() that calculates the norm (magnitude) of a vector of unknown length. Use your function to calculate

  1. \(\|(1, 2, 3)\|\)

  2. \(\|(4, 5, 6, 7)\|\)

Exercise 12.6

Euclid’s algorithm for computing the greatest common divisor (GCD) of two numbers \(x\) and \(y\) is

  1. Find the remainder \(r\) of \({x}\div{y}\)

  2. Set \(x = y\) and \(y = r\)

  3. 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:

  1. 14 and 245

  2. 2414 and 54145

Exercise 12.7

The following sequence converges to the square root of a positive number \(x\)

\[ x_{n+1} = \frac{1}{2} \left( x_n + \frac{x}{x_n} \right), \]

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

  1. \(\sqrt{144}\)

  2. \(\sqrt{12345}\)