In MATLAB, you can define a function by using the `function` keyword followed by the output variable, function name, and input arguments, as shown in the example below:
function output = myFunction(input)
output = input^2; % Example: squares the input value
end
What is a MATLAB Function?
A MATLAB function is a block of code designed to perform a specific task. Functions are integral to programming because they allow for code reusability and modular development. Unlike scripts, which execute commands sequentially, functions can accept input arguments and return outputs, leading to more versatile and maintainable code.
Importance of Functions
Understanding how to define a function in MATLAB is crucial for several reasons:
- Code Reusability: You can write a function once and reuse it multiple times throughout your code, saving time and effort.
- Modular Programming: Functions help break down complex problems into smaller, manageable pieces.
- Enhanced Readability: Well-defined functions make your code easier to read and understand, which is invaluable for debugging and collaboration.

Basic Syntax of a MATLAB Function
To define a function, you follow a specific syntax that includes the function keyword, input parameters, and optional outputs.
Structure of a Function Definition
The general format for a function definition in MATLAB is:
function [outputs] = functionName(inputs)
% Function description
end
Each component serves a unique purpose:
- function: Indicates that you're defining a new function.
- outputs: The variables that the function will return (can be one or multiple).
- functionName: The name you assign to your function, following MATLAB's naming conventions.
- inputs: The variables the function accepts as parameters.
Example of a Simple Function
Consider this example of a simple function that calculates the area of a circle:
function area = calculateArea(radius)
area = pi * radius^2; % Using MATLAB’s built-in constant pi
end
In this example, the function `calculateArea` takes a single input (the radius) and returns a single output (the area). Understanding how to define such functions is key to utilizing MATLAB effectively.

Inputs and Outputs in Functions
Defining Input Arguments
You can define multiple input arguments, allowing for more flexible functions. Here's how you can create a function that adds two numbers:
function result = addNumbers(a, b)
result = a + b; % Summing two input values
end
In this function, `a` and `b` are inputs, and the function outputs their sum as `result`.
Defining Output Arguments
Functions in MATLAB can return multiple outputs by specifying them in square brackets. For example, consider this function that performs basic operations:
function [sum, difference] = basicOps(a, b)
sum = a + b; % Sum of a and b
difference = a - b; % Difference of a and b
end
You can call this function and retrieve both outputs:
[s, d] = basicOps(10, 5); % s = 15, d = 5
Optional Arguments
Using Varargin
Sometimes, functions need to accept an undetermined number of input arguments. This flexibility can be achieved using `varargin`, as illustrated here:
function total = sumValues(varargin)
total = sum([varargin{:}]); % Summing all input values
end
This function sums all values passed to it regardless of how many there are.
Using Nargchk
To handle the number of input or output arguments precisely, you can use `nargin` and `nargout`:
function output = exampleFunction(a, b)
nargchk(2, 2, nargin); % Ensure exactly 2 input arguments
output = a * b; % Return product of a and b
end
This function checks that precisely two arguments are passed, ensuring it operates correctly.

Function Handles
What is a Function Handle?
A function handle is a MATLAB data type that allows you to refer to a function indirectly. This capability is useful for passing functions as arguments to other functions or for callbacks in GUI applications.
Creating a Function Handle
Creating a function handle is simple. For example:
fhandle = @sin; % Creating a handle for the sine function
result = fhandle(pi/2); % Result will be 1
In this snippet, `fhandle` refers to the `sin` function, which you can invoke just like you would with the original function.
Using Function Handles with Different Functions
You can also define your functions that accept function handles as arguments, allowing for greater flexibility:
function result = applyFunction(fhandle, value)
result = fhandle(value); % Applying the function handle to the value
end
This enables you to pass any function handle to `applyFunction`, making your code more dynamic.

Scope and Persistence
Local vs Global Variables
Variables defined within a function are local to that function. For example:
function myFunc()
locVar = 10; % Local variable
end
Here, `locVar` cannot be accessed outside `myFunc`, ensuring variable integrity.
Persistent Variables
If you need a variable to retain its value between function calls, you can declare it as persistent:
function counter()
persistent count; % Persistent variable
if isempty(count)
count = 0; % Initialize only once
end
count = count + 1; % Increment count
disp(count); % Display the current count
end
Every time you call `counter()`, it retains and increments `count`, demonstrating how to maintain state in your functions.

Best Practices for Writing Functions
Function Naming Conventions
When defining a function, it’s important to choose a descriptive name that clearly indicates its purpose. Avoid using vague names; instead, aim for clarity and expressiveness.
Documentation and Comments
Always include comments and a brief description at the start of your functions. This provides context for yourself and others who may read the code later:
function output = squareNumber(num)
% squareNumber returns the square of the input number
output = num^2; % Calculating square
end
Providing documentation makes your code more maintainable and easier to understand.
Testing Your Functions
Before using any function, it’s vital to test and debug it thoroughly. You can write test cases for various input scenarios to ensure the function behaves as expected. MATLAB also offers debugging tools that can help you find and fix errors effectively.

Conclusion
Learning how to define a function in MATLAB is an essential skill for anyone looking to leverage MATLAB for technical computing. Functions enhance code organization, make it reusable, and allow for complex calculations to be wrapped in simple-to-use interfaces. Start by implementing your functions, testing them, and gradually you will become proficient in MATLAB programming.

Additional Resources
For further learning, consult the [MATLAB documentation](https://www.mathworks.com/help/matlab/ref/function.html) and explore books or online courses that focus on MATLAB programming. Engaging with these resources will solidify your understanding and improve your coding capabilities.