A function in MATLAB is a reusable block of code that performs a specific task

Instead of writing the same lines of code over and over, you write them once inside a function, give that function a name, and call it whenever you need it. MATLAB functions live in their own files or in a script, take input values (called arguments), process them, and return output values. Once you understand the basic structure, you can build functions that do anything from straightforward math to controlling network equipment on a wired connection.

The simplest functions are the ones you write first. You do not need special tools or setup — just a text editor and MATLAB itself. The payoff is when ready: less repetition, easier debugging, and code that other people (or future you) can actually read.

Key Takeaways

  • A function starts with the word function, followed by what it returns, its name, and what it accepts as input.
  • The function body contains the actual code, and end marks where the function stops.
  • You can save a function in its own .m file (with the same name as the function) or inside a script file below the main code.
  • Call a function by typing its name with parentheses and arguments, just like sqrt(16) or myfunction(5, 10).
  • Functions can return one value, multiple values, or no values at all depending on what you need.

The basic structure of a MATLAB function

Every MATLAB function follows the same skeleton. The first line declares that you are writing a function, what it will return, what it is called, and what inputs it accepts:

function output = functionName(input1, input2)

Replace output with the name of what the function will return (or leave it blank if it returns nothing). Replace functionName with whatever you want to call it — keep it short and descriptive, like convertVoltage or checkConnection. Replace input1, input2 with the names of the values the function will receive. You can have zero inputs, one input, or many.

After that first line, write the code that does the work. At the end, type end to close the function. Here is a complete example:

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

This function takes two inputs (a and b), adds them together, stores the answer in result, and returns it. When you call addNumbers(3, 5), MATLAB runs the code inside, and you get back 8.

Saving your function in a file

MATLAB looks for functions in two places: in the current folder, or in a folder that MATLAB knows about (called the search path). The easiest approach is to save each function in its own file with a .m extension, using the exact same name as the function.

If your function is called addNumbers, save it in a file named addNumbers.m. MATLAB will find it automatically when you type addNumbers(3, 5) in the command window or in another script. If you save it with a different name, MATLAB will not find it, and you will get an error saying the function is undefined.

You can also put multiple functions in one file, but only the first function (the one at the top) can have the same name as the file. Any functions below it are called local functions and can only be used by the first function or by other functions in that same file. For learning, it is simpler to keep one function per file.

Functions that return multiple values

Sometimes you need a function to return more than one answer. MATLAB lets you do this by putting square brackets around the output names on the first line:

function [output1, output2] = functionName(input1) output1 = input1 * 2; output2 = input1 * 3; end

When you call this function, you capture both outputs by using square brackets on the left side: [result1, result2] = functionName(5). Now result1 holds 10 and result2 holds 15.

If you only want one of the outputs, you can ignore the others by using a tilde (~): [result1, ~] = functionName(5) captures only the first output and throws away the second. This is useful when a function returns more data than you need.

Calling a function and passing data to it

Once your function is saved and MATLAB knows where to find it, calling it is straightforward. Type the function name, open parentheses, list your inputs separated by commas, and close parentheses:

answer = addNumbers(7, 3)

MATLAB runs the function with 7 and 3 as the values for a and b, calculates the result, and stores 10 in the variable answer. You can also call a function without storing the result: addNumbers(7, 3) will run the function, but the answer disappears unless you printed it inside the function.

The inputs you pass do not have to be single numbers. You can pass arrays, strings, or even other variables. If you have a variable x = 12 and you call addNumbers(x, 5), MATLAB substitutes 12 for a and 5 for b inside the function.

Adding comments and making functions readable

A function that works is not the same as a function that someone else can understand. Add comments at the top explaining what the function does, what inputs it expects, and what it returns. In MATLAB, anything after a percent sign (%) is a comment and MATLAB ignores it:

% addNumbers: Takes two numbers and returns their sum % Inputs: a (number), b (number) % Output: result (number) function result = addNumbers(a, b) result = a + b; end

These comments do not change how the function works, but they make it clear to anyone reading the code (including you, six months from now) what the function is supposed to do. When you are writing functions that interact with network hardware or process data from sensors, clear comments become even more important because the stakes are higher if someone misuses the function.

Common mistakes when writing functions

The most common error is forgetting the end statement. MATLAB will not know where your function stops, and you will get a syntax error. Another frequent mistake is mismatching the filename and the function name — if your function is called myFunction but you save it as my_function.m, MATLAB will not find it.

A third mistake is forgetting to actually assign the result to the output variable. If you write a function that calculates something but never stores it in the output variable, the function returns nothing (or returns an empty value). Always make sure the last thing your function does is put the answer into the variable you declared at the top.

Finally, be careful with variable names inside functions. Variables inside a function are local — they only exist inside that function. If you create a variable called temp inside your function, it does not affect any variable named temp outside the function. This is usually a good thing because it prevents accidents, but it can confuse beginners who expect variables to be shared.

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() with empty parentheses. A function with no output looks like function myFunction(input1) with no assignment before the function name. You can even have both: function myFunction() with nothing before the name and nothing in the parentheses.

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 you call by name and pass data to. Scripts share variables with the workspace; functions keep their variables private. Use scripts for one-off tasks and functions when you need to reuse code or keep things organized.

Can I call one function from inside another function?

Yes. If you have a function called addNumbers and another called multiplyByTwo, you can write code inside multiplyByTwo that calls addNumbers. MATLAB will find and run it the same way it does from the command window.

What does the error "Undefined function or variable" mean?

MATLAB cannot find your function. Check that the filename matches the function name exactly (including uppercase and lowercase letters), that the file is saved in the current folder or on the search path, and that you typed the function name correctly when you called it.

Can I edit a function after I have saved it?

Yes. Open the .m file in the MATLAB editor, make your changes, and save it. The next time you call the function, MATLAB will use the updated version. You do not need to restart MATLAB or do anything special.