How to Create a Function in MATLAB

Ammar Ali Feb 02, 2024
How to Create a Function in MATLAB

This tutorial will discuss creating functions using the variable function in MATLAB.

Create a Function Using the Variable function in MATLAB

A function in Matlab consists of mainly three things output, input, and function name. To define a function, we use the variable function, and then we define the outputs, the function name, and the inputs of the function. After that, we will write our code inside the function. The function name should start with an alphabetic character, and a function name can contain numbers, digits, and underscores. To indicate the end of a function, we can use the variable end. For example, see the code below.

function outputs = function_Name(inputs)
    Your code
end

A function can have only one output. For example, let’s define a function that will accept an array of numbers, and the output of the function will be the average of the array. See the code below.

vect = [1 3 5]
averg = average(vect)


function a = average(v)
a = mean(v);
end

Output:

vect =

     1     3     5


averg =

     3

A function can also have two outputs. For example, let’s define a function that will accept one array, and it will give us the mean of the array and the standard deviation. See the code below.

vect = [1 3 5]
[averg, stanD] = average(vect)


function [a,s] = average(v)
a = mean(v);
s = std(v);
end

Output:

vect =

     1     3     5


averg =

     3


stanD =

     2

We can define a function in a script file, but we have to define it at the end of the code. You can also Define Multiple functions in a single file, and all of the functions should have to be at the end of the code. One function can also call another function. For example, you can define two functions, and the second function can call the first function. We can also define functions with input validation so that we can check the inputs. For example, let’s define a function that will check the input, whether it’s an integer or not, and if it’s an integer, it will perform the operation; otherwise, it will send an error. We can do that using the variable arguments. See the code below.

vect = 'a';
[averg, stanD] = average(vect)


function [a,s] = average(v)
arguments
        v {mustBeNumeric, mustBeFinite}
    end
a = mean(v);
s = std(v);
end

Output:

Error using Untitled>average
Invalid argument at position 1. Value must be numeric.

Error in Untitled (line 3)
[averg, stanD] = average(vect)

In the above code, we have passed a string instead of a numeric array, and Matlab has shown an error that says that the value must be numeric. Keep in mind that when you call a function, you should provide the specific inputs and outputs. For example, if we defined a function with two inputs and two outputs, we should define two inputs and two outputs during the function call; otherwise, it will show an error, but if you want to define a function with a variable number of outputs and inputs. We can do that using the varargin variable to define the variable inputs of a function. We can use the variable nargin that tells us how many inputs the user entered. After that, we can specify conditions for the inputs. For example, we can define requirements that if the user enters one input, this will be the output, and if the user enters two inputs, then this will be the output, and so on. For example, let’s define a function that will give us the number of inputs entered by the user. See the code below.

NumInputs('a',2,"start")

function NumInputs(varargin)
    disp("Number of inputs: " + nargin)
    celldisp(varargin)
end

Output:

Number of inputs: 3
 
varargin{1} =
 
a
 
 
varargin{2} =
 
     2

 
 
varargin{3} =
 
start

We can also define variable outputs in a function using the variable varargout, and we can keep track of how many outputs the user has defined using the variable nargout. For example, let’s define a function that will give us the mean and standard deviation. If the user defines only one output, the function will return only the mean of the array. If the user defines two output variables, the function will return the standard deviation and the array’s mean. See the code below.

v = [1 2 6];
[m]= AVGSTD(v)
[mean,st] = AVGSTD(v)

function [m,varargout] = AVGSTD(v)
    m = mean(v);
    if(nargout>1)
        varargout{1} = std(v);
    end
end

Output:

m =

     3


mean =

     3


st =

    2.6458

In the above code, we called the function AVGSTD() twice, the first time with only one output and the second time with two outputs. On the first call, the function only returned the mean, but on the second call, the function returned the mean and the standard deviation. We can also validate the number of outputs using the variable argument. For example, if the user tries to enter more than two variables in the output, we can show him an error that this function only accepts two outputs. We can also define reusable functions in Matlab, which will be stored in a file, and we can call them using the filename. To define such a function, we just have to name the Matlab file in the function’s name. For example, if the function has the name average, the Matlab file should have the same name. To call the function, we have to create another script file in the same directory where the function file has been placed, and we can call the function using its name inside the script file.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - MATLAB Function