Mastering MATLAB Functions
Function Basics
What Are Functions?
Think of a function like a recipe. You provide specific ingredients (inputs), the recipe gives clear instructions on what to do with them, and you end up with a finished dish (an output). In programming, a function is a self-contained block of code that performs a specific task. You give it some data, it processes that data, and it gives you back a result.
The main reason to use functions is to organize your code into reusable, modular pieces. This makes your programs cleaner, easier to understand, and simpler to debug.
Instead of writing the same lines of code over and over, you can write them once inside a function and then just "call" that function whenever you need it. This is a core concept in programming. In MATLAB, you've likely been using scripts so far. Let's see how they differ from functions.
Scripts vs. Functions
A script is a simple file containing a sequence of MATLAB commands. When you run a script, it's like typing those commands directly into the Command Window. Any variables a script creates are added to the main workspace, where they can be accessed and modified by any other script or command.
A function is different. It operates in its own private workspace. Variables created inside a function are temporary and exist only while the function is running. They don't appear in the main workspace and don't conflict with variables that have the same name elsewhere. Data gets into a function through input arguments, and results are passed out through output arguments.
| Feature | Script | Function |
|---|---|---|
| Workspace | Shares the main workspace | Has its own private workspace |
| Data Input | Accesses data from the main workspace | Receives data via input arguments |
| Data Output | Creates variables in the main workspace | Returns data via output arguments |
| Filename | Can be any valid filename | Must match the function name |
Anatomy of a Function
Every function in MATLAB starts with the function keyword. The structure follows a specific syntax that defines its inputs, outputs, and name.
function [outputArg1, outputArg2] = functionName(inputArg1, inputArg2)
% This is the body of the function.
% Code to calculate the outputs goes here.
outputArg1 = inputArg1 + 10; % Example calculation
outputArg2 = inputArg2 * 5; % Example calculation
end
Let's break that down:
function: This keyword always starts the function definition.[outputArg1, outputArg2]: These are the output arguments, enclosed in square brackets. If there's only one output, the brackets are optional.functionName: This is the name of your function. You'll use this name to call it.(inputArg1, inputArg2): These are the input arguments, enclosed in parentheses. This is the data you pass into the function.end: This keyword marks the end of the function's code.
Creating Your First Function
Let's create a simple function that adds two numbers together.
- Open a new script file in the MATLAB Editor.
- Type the function code into the file.
- Save the file. This is a critical step: The file name must be exactly the same as the function name, followed by
.m. For our example, you must save the file asaddTwoNumbers.m.
% In a file named addTwoNumbers.m
function sumResult = addTwoNumbers(num1, num2)
% This function takes two numbers as input
% and returns their sum.
sumResult = num1 + num2;
end
Once the file is saved in your current MATLAB folder, you can call it from the Command Window or from another script, just like any built-in MATLAB function.
>> total = addTwoNumbers(5, 3)
total =
8
Here's one more example. A function to calculate the area of a circle given its radius. Notice it has one input and one output.
% In a file named calculateCircleArea.m
function area = calculateCircleArea(radius)
% Calculates the area of a circle.
area = pi * radius^2;
end
You would call it from the Command Window like this:
>> circleArea = calculateCircleArea(10)
circleArea =
314.1593
Now you know the essential difference between scripts and functions and how to build your own simple functions. Let's test your understanding.
What is the primary difference between a script and a function in MATLAB regarding how they handle variables?
Which line of code correctly defines a function named calcPower that takes two inputs, base and exponent, and produces one output, result?