Tutorial

How to Define Functions in MATLAB

A function is a reusable piece of code characterized by a name, a set of inputs, and a set of outputs.

Description

Functions are a core concept in MATLAB programming. They encapsulate the implementation of an operation, so the caller just need to know what a function does, but not how.

A function definition consists of:

  1. The keyword function
  2. Zero or more output variables
  3. The name of the function
  4. Zero or more input variables
The name of the function must be a valid identifier.

Syntax

The syntax to declare a function is as follows:

function [output1,…,outputN] = myfunc1(input1,…,inputN)
% Body of the function
end

If a function has only one output, best practices suggest to omit the square brackets, and if there are no outputs, the name of the function goes immediately after the keyword function.

% Function with one output
function output = myfunc2(input1,…,inputN)
end
% Function with zero outputs
function myfunc3(input1,…,inputN)
end

You can omit the parentheses if there are no inputs, but I recommend to always use them. In some cases the end keyword is not required, but I also recommend to always use it.

File

Functions are saved in .M files. The first executable line in the file must be the definition of the function, and the name of the file must match the name of the function.

The first function in a .M file is called the main function. Each .M file can also contain local functions and nested functions.

Further reading

I recommend the following books to learn more on functions in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a Textbook Excellence Award. The sixth chapter covers user-defined functions, scope of variables, debugging, and other aspects related to the development of MATLAB programs.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 6 explains how to create functions, including local functions, anonymous functions, and nested functions.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc function;

Exercise

Define a function called mysum that receives two inputs and returns one output.

Source code

I hope you have learned how to define functions in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.