If you have started learning MATLAB, you have probably written a few lines of code to solve a mathematical problem or perform a calculation. That works well for small tasks, but what happens when you need to repeat the same calculation ten times or use it in a different program?
This is where functions come in.
A function lets you write a piece of code once and use it whenever you need it. It also makes your programs easier to read, test, and update. In this guide, I’ll explain how MATLAB functions work, show you how to create your own, and walk through a few examples you can try on your computer.
What Is a Function in MATLAB?
Think of a function as a small tool that performs a particular job. You give it some information, it processes that information, and it returns a result if one is needed.
For example, imagine calculating the area of a rectangle several times. You could write the formula repeatedly, but that would make your code longer than necessary. Instead, you can create a function that accepts the length and width and calculates the area for you.
MATLAB functions are useful when you want to:
- Reuse calculations without copying the same code.
- Divide a complicated problem into smaller steps.
- Make errors easier to find and fix.
- Keep mathematical formulas organised.
- Use the same calculation in different scripts or projects.
There is an important difference between a script and a function. A script runs commands in the current workspace, while a function has its own workspace and receives information through its input arguments.
If you want to explore this distinction further, MathWorks explains it in its official guide to scripts and functions.
Understanding MATLAB Function Syntax
Before writing your first function, it helps to understand how MATLAB expects the code to be structured. The syntax might look unfamiliar at first, but it becomes straightforward once you have used it a few times.
Here is a simple example:
function result = doubleNumber(x)
result = x * 2;
end
Let’s break it down.
functiontells MATLAB that you are defining a function.resultis the output variable that holds the answer.doubleNumberis the function’s name.xis the input argument.endmarks the end of the function.
When you call this function with the value 5, MATLAB multiplies the input by two and returns 10.
The general structure is:
function output = functionName(input)
% Write your calculations here
output = input;
end
You do not have to use exactly one input and one output every time. A function can accept several inputs, return multiple results, or work without inputs altogether. The official MATLAB function reference covers the different forms.
For now, remember the basic idea: inputs provide the information, the function performs the calculation, and outputs carry the result back to the calling code.
How to Create Your First MATLAB Function
The easiest way to understand functions is to create one and run it yourself. Let’s start with a function that calculates the square of a number.
Step 1: Open the MATLAB Editor
Open MATLAB and select New Script from the Home tab. This opens an editor where you can write your code.
Enter the following:
function result = squareNumber(x)
result = x^2;
end
The function takes a number called x, raises it to the power of two, and stores the answer in result.
Step 2: Save the File
Save your file as squareNumber.m.
This part matters more than you might expect. For a standalone function, the filename should match the name of the first function in the file. If you call your function squareNumber, saving it under a different filename can prevent MATLAB from finding it as expected.
You can read more about this rule in the MathWorks guide to creating functions in files.
Step 3: Run the Function
Make sure the file is saved in your current folder or somewhere on the MATLAB search path. Then enter this command in the Command Window:
answer = squareNumber(5)
MATLAB displays:
answer =
25
That is your first working function.
You can try other values without changing the function itself:
squareNumber(3)
squareNumber(10)
squareNumber(-4)
The results are 9, 100, and 16.
Step 4: Try a Vector Input
There is one small detail worth understanding here. The ^ operator performs matrix power, so the original function is intended for a scalar input.
If you want to square every element in a vector, use the element-wise operator .^ instead:
function result = squareElements(x)
result = x.^2;
end
Save this function as squareElements.m, then run:
squareElements([1 2 3 4])
MATLAB returns:
ans =
1 4 9 16
This is a useful example of why you should test functions with the types of data you expect to use. A calculation that works for a single number may need a different operator when you work with arrays.
Creating a Function with Multiple Inputs
Many calculations depend on more than one value. Fortunately, MATLAB makes it easy to pass several inputs to a function.
Let’s use the area of a rectangle as an example.
Create a file named rectangleArea.m and enter:
function area = rectangleArea(length, width)
area = length * width;
end
The function accepts two inputs: length and width. It multiplies them and returns the result.
To calculate the area of a rectangle with a length of 8 and a width of 4, run:
result = rectangleArea(8, 4)
The answer is 32.
You can use the same function for other dimensions:
area1 = rectangleArea(5, 3);
area2 = rectangleArea(10, 6);
area3 = rectangleArea(7.5, 2);
Each call uses the same formula, but the result changes according to the supplied values.
Pay attention to the order of your inputs. MATLAB assigns arguments according to their positions in the function definition. In this example, the first value becomes length and the second becomes width.
Also, * performs matrix multiplication when used with matrices. If you need to multiply corresponding elements in two arrays, you may need .* instead.
How to Return Multiple Outputs
Sometimes a function needs to provide more than one answer. Instead of writing separate functions, you can return several outputs from the same calculation.
Suppose you want to find both the sum and the average of a set of numbers. Create a file called calculateStats.m and add the following code:
function [total, average] = calculateStats(numbers)
total = sum(numbers);
average = mean(numbers);
end
Now call the function:
[dataTotal, dataAverage] = calculateStats([10 20 30 40]);
The results are:
dataTotalis100.dataAverageis25.
The square brackets in the function definition tell MATLAB that the function returns two outputs. When calling it, you can use another pair of square brackets to collect both results.
If you only need the total, you can request the first output:
dataTotal = calculateStats([10 20 30 40]);
MATLAB returns 100.
I find that meaningful variable names make examples like this much easier to follow. Names such as total, average, and numbers explain what the code is doing without requiring lengthy comments.
Using Local Functions in MATLAB Scripts
You do not always need to save every function in a separate file. MATLAB also supports local functions, which are defined within a script and can help with smaller projects.
For example:
values = [2 4 6 8];
result = doubleValues(values);
disp(result);
function output = doubleValues(input)
output = input .* 2;
end
This script creates a vector, passes it to a local function, and displays the result.
The output is:
4 8 12 16
A local function is only available within the file where it is defined. You cannot normally call it directly from the Command Window or from an unrelated file.
The placement of local functions also depends on your MATLAB release. Before R2024a, local functions in scripts must appear after all the script code. In R2024a and later, they can appear elsewhere in the script, subject to MATLAB’s function-definition rules.
MathWorks explains these details in its guide to local functions in scripts.
If you are just getting started, I recommend using separate function files for calculations you want to reuse. Local functions are especially handy when a helper calculation only belongs to one script.
What Are Anonymous Functions?
Sometimes you need a quick calculation but do not want to create a separate file. MATLAB’s anonymous functions are useful for these situations because they let you define a function in a single expression.
For example:
square = @(x) x.^2;
You can now calculate the square of a number by entering:
square(6)
The result is 36.
The @ symbol creates a function handle, and (x) identifies the input argument. The expression after it specifies what the function should calculate.
Anonymous functions can also accept multiple inputs:
addNumbers = @(a, b) a + b;
result = addNumbers(5, 7);
The result is 12.
They are also useful with MATLAB’s built-in numerical tools. For example, you can calculate a definite integral using:
result = integral(@(x) x.^2, 0, 1);
This calculates the integral of x2x^2 between zero and one, giving approximately 0.3333.
However, anonymous functions are best suited to short expressions. If you need several calculations, loops, or complicated conditions, a conventional function file is usually easier to understand and maintain. See the MATLAB anonymous functions guide for more details.
Common MATLAB Function Errors and How to Fix Them
When you first start writing functions, small mistakes can lead to confusing error messages. The good news is that many of these problems have straightforward solutions.
Here are a few things to check when your function does not work as expected.
The Filename Does Not Match the Function Name
If your function begins with:
function result = calculateArea(x)
save the file as calculateArea.m.
Check that the function name and filename match, and make sure you are calling the function using the correct spelling.
MATLAB Cannot Find the Function
If MATLAB says that a function is unrecognised, the file might not be in the current folder or on the search path.
To check your current folder, enter:
pwd
To see which file MATLAB finds for a function, run:
which calculateArea
If MATLAB cannot locate the file, move to the correct folder or add the folder containing your function to the MATLAB search path.
A Variable Is Undefined Inside the Function
Imagine that you created a variable named radius in a script and then tried to use it inside a separate function without passing it in.
That will not normally work because a function has its own workspace.
Instead, pass the value as an input:
function area = circleArea(radius)
area = pi * radius^2;
end
Call it using:
area = circleArea(5);
This makes the function more independent and easier to reuse. MathWorks explains this behaviour in its documentation on base and function workspaces.
The Function Produces an Unexpected Answer
Check the formula, the order of your inputs, and the operators you have used. For example, x^2 and x.^2 can produce different behaviour when x is an array.
A simple way to check your work is to test values for which you already know the answer. If a function calculates the area of a rectangle, try dimensions of 5 and 4 and check whether the result is 20.
You should also consider what happens when an input is zero, negative, or outside the range your calculation is designed to handle.
For more advanced functions, MATLAB supports argument validation through arguments blocks. These can help you check input types, sizes, and other requirements before carrying out a calculation. The official argument validation reference explains how this works.
Tips for Writing Better MATLAB Functions
Once your functions are working, a few good habits can make your code much easier to manage. These habits are particularly useful when you start working on larger assignments or projects involving several calculations.
- Choose meaningful names. Names such as
calculateAverageandconvertTemperatureare easier to understand thanf1ortest2. - Keep functions focused. Try to make each function responsible for one main task.
- Use comments where they help. Explain the purpose of a calculation or any assumptions that might not be obvious.
- Pass inputs explicitly. Avoid relying on variables created elsewhere in your workspace.
- Test different cases. Check normal inputs, boundary values, and invalid inputs where appropriate.
- Choose the right type of function. Use standalone functions for reusable calculations, local functions for file-specific tasks, and anonymous functions for short expressions.
As your programs grow, you can also use MATLAB’s testing tools to check your functions automatically. MathWorks provides function-based unit testing, which allows you to write tests that compare actual results with expected results.
For example, a test for a rectangle-area function could check that dimensions of 5 and 4 return 20. Another test could check that a rectangle with one zero dimension has an area of zero.
Testing is especially helpful when you modify a function later. It gives you a way to check that your changes have not accidentally broken something that was already working.
How MATLAB Functions Can Help with Assignments
Functions are useful in university coursework because they help you organise a solution into manageable parts. Rather than placing every calculation in one long script, you can separate different stages of a problem into individual functions.
For example, an engineering assignment might involve processing input data, carrying out a numerical calculation, and analysing the results. You could write a separate function for each stage and use a script to bring everything together.
This structure makes it easier to identify where a problem occurs and test each part independently. It also helps you explain how your solution works.
If you are struggling with a complex MATLAB project, resources offering matlab code assignment writing may provide additional guidance. Use external resources to clarify difficult concepts and check your approach, while making sure your submitted work follows your institution’s academic integrity requirements.
Frequently Asked Questions
Can I create a MATLAB function without inputs?
Yes. A function can run without receiving any input arguments.
function displayMessage()
disp('Welcome to MATLAB!');
end
Save the file as displayMessage.m and run it using:
displayMessage()
MATLAB displays the message without needing any additional information.
Can a MATLAB function return more than one value?
Yes. You can define multiple output arguments inside square brackets.
function [sumValue, difference] = calculate(a, b)
sumValue = a + b;
difference = a - b;
end
Calling [s, d] = calculate(10, 4) gives s = 14 and d = 6.
What is the difference between a script and a function?
A script runs commands in the workspace from which it is executed. A function has its own workspace and can accept inputs and return outputs.
Scripts are useful for running a sequence of commands, while functions are often a better choice when you want to reuse a calculation in different places.
Do I need to use end in every MATLAB function?
Including end is a good habit because it clearly marks where the function finishes. MATLAB permits its omission in some function-file situations, but it is required in certain structures, including local functions in scripts and functions containing nested functions.
For beginner projects, using end consistently helps keep your code organised.
Can I create a function directly in the Command Window?
You can create an anonymous function directly in the Command Window without saving a separate file.
cube = @(x) x.^3;
cube(3)
The result is 27.
For a conventional named function that you want to reuse across scripts, creating and saving an .m file is generally the better approach.
Final Thoughts
Learning to create functions in MATLAB takes a little practice, but the basic idea is simple: write a calculation once, give it a clear name, and reuse it whenever you need it.
Start with a small example, such as squaring a number or calculating the area of a rectangle. Once that feels comfortable, experiment with multiple inputs, multiple outputs, and anonymous functions.
Pay attention to filenames, input arguments, and the difference between matrix and element-wise operations. These details can save you considerable time when debugging your code.
Most importantly, try writing functions for calculations you already understand. The more you practise, the easier it becomes to organise your programs, understand errors, and build MATLAB solutions that are clear, reliable, and easy to maintain.


