A function in MATLAB is a block of code that does one specific job and can be reused whenever you need it
A function is a set of commands grouped together under a name. Instead of typing the same calculations or steps over and over, you write them once in a function, give that function a name, and then call it by name whenever you need those steps to run. MATLAB functions live in their own files and can accept input (called arguments) and return output (called return values).
The basic structure is simple: you write the function code in a file, save that file with a specific name, and then use it in your main script or in the command window. MATLAB knows to look for the function by its filename, so naming matters.
Key Takeaways
- A function file must be saved with the same name as the function itself, followed by .m — so a function called calculateArea goes in a file named calculateArea.m.
- Every function starts with the word function, followed by what it returns, then the function name and what inputs it takes.
- The function body contains the actual code that does the work, and end marks where the function stops.
- You call a function by typing its name with parentheses and any inputs, just like you would call a built-in MATLAB command.
The basic structure: function declaration, body, and end
Every MATLAB function follows the same pattern. The first line declares that this is a function, what it will return, what its name is, and what inputs it expects. Here is a simple example:
function output = myFunction(input1, input2) output = input1 + input2; end
The word function tells MATLAB this is a function definition. Then comes output =, which is the name of the variable the function will return. Then myFunction is the name you will use to call it. Inside the parentheses, input1 and input2 are the values the function expects to receive. The body of the function (the lines between the first line and end) contains the actual work. The end statement closes the function.
When you save this code, the filename must match the function name exactly: myFunction.m. MATLAB uses the filename to find the function when you call it, so if the names do not match, MATLAB will not find your function.
How to name your function file correctly
The filename and the function name must be identical. If your function is called calculateArea, save the file as calculateArea.m. If you name it calculate_area.m or CalculateArea.m, MATLAB will not recognize it as the function calculateArea.
Function names should start with a letter and can contain letters, numbers, and underscores. Avoid spaces and special characters. Keep names short but descriptive — addNumbers is better than a, and convertTemperature is better than convert.
Save your function file in a folder that MATLAB can find. The simplest approach is to save it in your current working directory (the folder MATLAB is currently looking at). You can check your current directory in the Current Folder panel on the left side of the MATLAB window, or type pwd in the command window to see the path.
Writing a function that takes inputs and returns outputs
Most functions need to receive information and send back a result. The inputs go in parentheses after the function name, and the output goes on the left side of the equals sign in the first line.
Here is a function that calculates the area of a rectangle:
function area = calculateRectangleArea(length, width) area = length * width; end
This function takes two inputs (length and width), multiplies them together, and stores the result in a variable called areaarea is what gets returned when you call the function. To use it, you would type in the command window or in another script: result = calculateRectangleArea(5, 3). MATLAB would multiply 5 by 3, return 7, and store it in the variable result.
A function can return more than one output. Separate the output names with commas and wrap them in square brackets:
function [area, perimeter] = calculateRectangleProperties(length, width) area = length * width; perimeter = 2 * (length + width); end
When you call this function, you capture both outputs: [a, p] = calculateRectangleProperties(5, 3). Now a holds the area and p holds the perimeter.
Calling your function from a script or the command window
Once your function is saved in a file with the correct name, you can use it anywhere in MATLAB. In the command window, type the function name with your inputs in parentheses. If your function is called calculateRectangleArea and you saved it as calculateRectangleArea.m, you would type:
calculateRectangleArea(5, 3)
MATLAB runs the function with inputs 5 and 3, calculates the area, and displays the result (15) in the command window. If you want to store the result in a variable, add the variable name and an equals sign:
myArea = calculateRectangleArea(5, 3)
You can also call your function from inside another script. Create a new script file, and in that script, call your function just as you would in the command window. MATLAB will find the function as long as it is in the current directory or in a folder on MATLAB's search path.
Common mistakes when writing functions
The most frequent error is a mismatch between the filename and the function name. If you write a function called myCalc but save it as my_calc.m, MATLAB will say the function is not found. Always check that the filename matches the function name exactly, including capitalization.
Another common mistake is forgetting the end statement. Every function must end with end on its own line. Without it, MATLAB will not know where the function stops, and you will get a syntax error.
A third mistake is not assigning the result to the output variable. If you write a function that calculates something but never assign it to the output variable named in the first line, the function will not return anything useful. For example, this function does not work correctly:
function result = addNumbers(a, b) sum = a + b; end
The problem is that the output variable is called result, but you calculated sum. Change it to result = a + b; so the output variable holds the answer.
Adding comments to explain what your function does
It is good practice to add comments at the top of your function that explain what it does, what inputs it expects, and what it returns. In MATLAB, anything after a percent sign (%) is a comment and will not run as code.
function area = calculateRectangleArea(length, width) % This function calculates the area of a rectangle % Inputs: length and width (numbers) % Output: area (a number) area = length * width; end
These comments do not affect how the function runs, but they make it much easier for you (or someone else) to understand what the function is supposed to do when you read it later. Comments are especially useful if your function is complex or if you plan to share it with others.
Frequently Asked Questions
Can a function have no inputs or no outputs?
Yes. A function with no inputs looks like function output = myFunction() with empty parentheses. A function with no outputs looks like function myFunction(input) with nothing before the equals sign. You can even have both: function myFunction() with no inputs and no outputs — though this is less common.
Where should I save my function file?
Save it in your current working directory (the folder MATLAB is currently looking at). You can see this folder in the Current Folder panel on the left, or type pwd in the command window. You can also save it in any folder that is on MATLAB's search path, but the current directory is the simplest option when you are starting out.
What is the difference between a script and a function?
A script is a file of MATLAB commands that runs from top to bottom. A function is a reusable block of code that takes inputs and returns outputs. Scripts do not have a function declaration line, and they do not return values. Use scripts for one-time tasks and functions for code you want to reuse.
Can I call one function from inside another function?
Yes. If you have a function called calculateArea and another called calculatePerimeter, you can call calculateArea from inside calculatePerimeter if you need to. MATLAB will find the function the same way it finds any other function.
What happens if I change my function and save it?
MATLAB will use the new version the next time you call the function. If you have already run the function in the command window, you may need to clear MATLAB's memory by typing clear all to make sure it loads the updated version, though this is not always necessary.