What a function is and why you write one

A function in MATLAB is a block of code that does one job and can be run as many times as you need without rewriting it. Instead of typing the same ten lines of code five times in your script, you write a function once, give it a name, and call that name whenever you need it. Functions take input (called arguments), do something with that input, and send back output (called a return value).

The real benefit shows up when your code grows. A script with one hundred lines of repeated calculations becomes hard to read and dangerous to edit — change one line and you have to change it in five places. A script that calls the same function five times stays short and clear. If you find a mistake in the function, you fix it once and the fix works everywhere.

MATLAB functions live in their own files or at the end of your script. When you call a function by name, MATLAB jumps to that code, runs it with the values you gave it, and comes back with the result. This guide shows you how to write that function, what each part does, and how to call it correctly.

Key Takeaways

  • A function starts with the word function, followed by what it returns, its name, and what it takes as input in parentheses.
  • The function body contains the actual code, and return or assignment to the output variable sends the result back to the caller.
  • Each function should live in its own file with the same name as the function, saved with the .m extension.
  • You call a function by typing its name with the input values in parentheses, just like result = myFunction(5, 10).
  • Comments at the top of your function explain what it does, what input it expects, and what it returns — this saves time later.

The basic structure of a MATLAB function

Every MATLAB function follows the same pattern. The first line tells MATLAB this is a function, what it will return, what its name is, and what input it accepts:

function output = functionName(input1, input2)

Replace output with the name of the variable that holds your result. Replace functionName with what you want to call this function. Replace input1, input2 with the names of the values the function needs — you can have one input, no inputs, or many inputs.

After that first line comes the body of the function — the actual code that does the work. At the end, you assign the result to the output variable (the one you named on the first line). MATLAB automatically sends that value back to whoever called the function. Then you type end to mark where the function stops.

Here is a complete, working example. This function takes two numbers and returns their sum:

function result = addNumbers(a, b) result = a + b; end

That is the whole thing. When you call addNumbers(3, 5), MATLAB runs the code inside, adds 3 and 5, stores 8 in result, and sends 8 back to you.

Where to save your function and how to name the file

MATLAB needs to find your function when you call it. The safest way is to save each function in its own file, with the filename matching the function name exactly and ending in .m. If your function is called addNumbers, save it in a file called addNumbers.m.

Save this file in the same folder as the script that calls it, or in a folder that MATLAB knows to search. When you open MATLAB, it searches the current folder first. You can see the current folder at the top of the MATLAB window — it usually says something like C:\Users\YourName\Documents\MATLAB. Put your function file there.

If you have many functions, create a subfolder called functions inside your main MATLAB folder, save all your functions there, and tell MATLAB to search that folder. Go to the Home tab, click Set Path, click Add Folder, choose your functions folder, and click Save. MATLAB will now find any function in that folder.

You can also write a function at the bottom of the same script that uses it, but only if that script is the only one that needs it. For anything you might reuse, a separate file is clearer and safer.

Writing a function that takes multiple inputs and returns multiple outputs

Functions do not have to return just one value. You can return two, three, or more. You can also take in as many inputs as you need. The syntax changes slightly but the idea stays the same.

If your function returns multiple outputs, list them in square brackets on the first line:

function [output1, output2] = functionName(input1, input2, input3)

Inside the function, assign values to both output1 and output2. When you call the function, catch both results:

[result1, result2] = functionName(5, 10, 15);

Here is a real example. This function takes a list of numbers and returns both the average and the highest value:

function [average, maximum] = analyzeData(numbers) average = mean(numbers); maximum = max(numbers); end

When you call it with [avg, peak] = analyzeData([2, 5, 8, 3]), MATLAB calculates the average (4.5) and the maximum (8), stores them in avg and peak, and you can use both values afterward.

Adding comments to explain what your function does

Comments are lines that MATLAB ignores — they are just for you and anyone else reading the code. Start a comment with %. Put comments at the very top of your function to explain what it does, what each input means, and what each output is. This takes thirty seconds to write and saves hours of confusion later.

Here is the analyzeData function with helpful comments:

% analyzeData: Calculate the average and maximum of a list of numbers % Input: numbers — a row or column vector of numeric values % Output: average — the mean of all values % Output: maximum — the largest value in the list function [average, maximum] = analyzeData(numbers) average = mean(numbers); maximum = max(numbers); end

When you or someone else opens this file six months from now, those comments tell you exactly what the function expects and what it gives back. Without them, you have to read the code itself to figure it out.

Calling your function from a script

Once your function is written and saved, calling it is straightforward. Type the function name, put your input values in parentheses, and assign the result to a variable if you need it later:

sum_result = addNumbers(7, 3);

MATLAB jumps to your function file, runs the code with 7 and 3 as the inputs, and stores the result (10) in sum_result. You can then use sum_result in the rest of your script.

If you do not need the result, you can call the function without assigning it to anything:

addNumbers(7, 3);

MATLAB still runs the function, but the result disappears. This is useful if your function does something like plotting a graph or saving a file, where the "result" is an action rather than a number.

You can also use the result directly in a calculation without storing it first:

total = addNumbers(7, 3) + addNumbers(5, 2);

MATLAB calls addNumbers(7, 3), gets 10, calls addNumbers(5, 2), gets 7, adds them together, and stores 17 in total.

Common mistakes and how to avoid them

The most common mistake is a mismatch between the filename and the function name. If your function is called addNumbers but you save the file as add_numbers.m or AddNumbers.m, MATLAB will not find it. The filename must match exactly, including capital letters. MATLAB is case-sensitive on most computers.

Another frequent error is forgetting the end statement at the bottom of the function. MATLAB needs to know where the function stops, especially if you have multiple functions in one file. If you forget end, MATLAB gets confused about where one function ends and the next begins.

A third mistake is passing the wrong number of inputs. If your function expects three inputs but you call it with two, MATLAB stops and tells you there is a mismatch. Count the inputs on the first line of your function definition, and make sure you provide exactly that many when you call it.

Finally, do not forget to assign the result to the output variable inside the function. If you calculate a value but never assign it to the output variable name, MATLAB has nothing to send back. The line result = a + b; is what makes the result available to the caller.

Frequently Asked Questions

Can a function have no inputs or no outputs?

Yes to both. A function with no inputs looks like function output = myFunction() — the parentheses are empty. A function with no outputs looks like function myFunction(input) — you skip the output part entirely. You might use a function with no output if it just plots something or saves a file.

What is the difference between a function and a script?

A script is a list of commands that MATLAB runs from top to bottom. A function is a reusable block that takes input, does something, and returns output. Scripts are good for one-time tasks; functions are good for code you use more than once. Functions also keep their variables separate from the rest of your code, which prevents accidental conflicts.

Can I call a function from inside another function?

Yes. Functions can call other functions. If you have a function called addNumbers and another called multiplyNumbers, you can write code inside multiplyNumbers that calls addNumbers. MATLAB handles the nesting automatically.

What happens if I give my function the same name as a built-in MATLAB function?

MATLAB will use your function instead of the built-in one, which usually causes problems. Avoid naming your function sum, mean, plot, or any other MATLAB command. If you are not sure whether a name is taken, type which functionName in the command window — MATLAB will tell you if it finds a built-in function with that name.

How do I test my function to make sure it works?

Write a straightforward script that calls your function with known inputs and checks the output. For example, if your function adds two numbers, call it with addNumbers(2, 3) and verify that it returns 5. Start with straightforward inputs where you know the answer, then try edge cases like zero, negative numbers, or very large numbers.