5.6: Functions with Multiple Outputs
- Page ID
Tags recommended by the template: article:topic
By Carey A. Smith
Matlab functions can have more than one output variable. For example, max(a) is a built-in function. It can be used as follows:
a = [0, 2, -1, 4.2, 2.1, 0.7]
With 1 output argument, it returns the maximum value:
a_max = max(a)
a_max = 4.2
With 2 output values, it returns the maximum value and the index in a of the maximum value:
[a_max, idx_max] = max(a)
a_max = 4.2 % The maximum value
idx_max = 4 % The maximum is the 4th element of a
When 2 or more output values, they are listed in square brackets [ ] as a vector.
A function with 2 outputs that computes statistics of a vector
function [x_mean, x_std_dev] = stats(x)
% Compute the mean and standard deviation of vector x
x_mean = mean(x); % mean = average
x_std_dev = std(x); % standard deviation
The first line of the function specifies the 2 output values in square brackets, which is consistent with how it is called:
[a_mean, a_std_dev] = stats(a)
Test it for a = [0, 2, -1, 4.2, 2.1, 0.7]
Note that “a” is the name of the vector in the main workspace, while "x" is the name of the local variable inside the function.
Also, the variables inside the function are x_mean and x_std_dev, so that they are different than the names of the built-in function's variables mena() and std().
The outputs are:
a_mean = 1.3333
a_std_dev = 1.837
Write a function called sum_diff.m that has 2 inputs, x and y, and 2 outputs:.
xy_sum (=the sum of vectors x and y)
xy_diff (= the difference of vectors x and y).
Write a 2nd m-file that tests your function with these vectors:
x = -2:2:6;
y = 1:1:5;
The test code needs to save both outputs with code like this:
[xy_sum, xy_diff] = sum_diff_YourName(x, y)
Work out the solution.
This video provides additional information:
%% The following data is from the Camroasa Water District's 2020 Water Quality report.
% (1pt) Define this vector of chloride levels from imported water and from wells:
Chloride = [52 113 122 45 83 133];
% Read the help for the max() function by typing this:
% (2 pts) Use this form to determine both the maximum value and the index of the maximum:
[Mx, Idx_max] = max(Chloride) % Returns the index corresponding to the maximum value
% (1 pt) Verify that the index is correct with this line:
%% (3 pts) Then use a similar form to determine the minimum and the index of the minimum. Verify that the index of the minimum is correct.
% The minimum function is min()
Work out the code for this exercise.