BudiBadu Logo
Samplebadu

MATLAB by Example: Functions

R2023b

Functions allow you to modularize code. This example shows how to define functions with inputs and outputs.

Code

% Function definition must be at the end of a script
% or in a separate file named myStats.m

function [avg, stdev] = myStats(x)
    % Calculates mean and standard deviation
    n = length(x);
    avg = sum(x) / n;
    stdev = sqrt(sum((x - avg).^2) / (n - 1));
end

% Calling the function
data = [1, 5, 8, 12, 20];
[m, s] = myStats(data);

fprintf('Mean: %.2f, Std Dev: %.2f\n', m, s);

Explanation

Functions in MATLAB are defined using the function keyword. The first line, known as the function signature, specifies the output arguments, the function name, and the input arguments. Unlike many other languages, MATLAB functions can return multiple values directly, which are assigned to a vector of variables in the calling scope, like [out1, out2] = func(in).

Historically, each function had to be in its own file with the same name as the function. However, modern MATLAB allows local functions to be defined at the end of a script file. Variables defined inside a function are local to that function and do not pollute the global workspace, providing necessary encapsulation.

Documentation is easily added to functions by including comments immediately after the function header. These comments are displayed when a user types help function_name in the Command Window. This is a standard practice for creating maintainable and shareable code libraries.

Code Breakdown

4
function [avg, stdev] = ... declares a function that returns two values.
12
[m, s] = myStats(data) captures the two returned values into variables m and s.