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:
- The keyword
- Zero or more output variables
- The name of the function
- Zero or more input variables
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 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.
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.
I recommend the following books to learn more on functions in MATLAB.
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.
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.
- How to Define Functions in MATLAB
- How to Call a Function in MATLAB
- How to Add Help Documentation to a Function in MATLAB
- Local Functions in MATLAB
- Nested Functions in MATLAB
- Visibility of Nested Functions in MATLAB
- Private Functions in MATLAB
- Anonymous Functions in MATLAB
- Inside the Handle of Anonymous Functions in MATLAB
- Functions with Variable Input Arguments in MATLAB
- Functions with Variable Output Arguments in MATLAB
- How to Validate the Number of Input Arguments Passed to a Function in MATLAB
- How to Validate the Number of Output Arguments Passed to a Function in MATLAB
Define a function called
mysum that receives two inputs and returns one output.
A possible solution could be:
function R = mysum(x,y) end
I hope you have learned how to define functions in MATLAB. The source code developed in this tutorial is available at this page.