Table of Contents
Overview
In MATLAB you write your own code primarily in two forms, scripts and functions. They both live in files, both can be edited in the MATLAB Editor, and both can be run from the Command Window, but they behave quite differently. Understanding the difference between them is essential, because it strongly affects how variables are created and used, how reusable your code becomes, and how easy it is to debug or extend.
This chapter focuses specifically on how scripts and functions differ, when to use each, and how to move from simple script based work toward more structured function based programs.
What a Script Is
A script is simply a sequence of MATLAB commands saved in a file and executed as if you had typed those commands directly in the Command Window. A script file has the extension .m and contains normal MATLAB code.
For example, imagine you type the following commands in the Command Window:
a = 10;
b = 5;
c = a + b
If you copy these three lines into a file named myscript.m and save it, myscript.m is a script. When you type myscript at the Command Window, MATLAB executes the commands in the file in order.
The key features of a script are that it does not declare inputs or outputs, and it shares the base workspace with the Command Window. Any variable that the script creates or modifies becomes a variable in the base workspace, and any variable that already exists in the base workspace can be used by the script.
If you run:
x = 3;
myscript
inside myscript you could refer to x even though x is never defined inside the file itself, because the script sees and uses the variables that already exist in the base workspace.
Variable Scope in Scripts
Since scripts share the base workspace, their variables are globally visible in an informal sense. Every variable that is created in a script will remain available after the script finishes, so you can inspect it in the Workspace browser or use it in later commands.
For example:
clear
myscript
whos
will show a, b, and c listed in the base workspace, because the script created them there.
This can be very convenient for quick experimentation and for interactive exploration, because you can run parts of a script, inspect variables, change some values, and rerun sections. However, for larger programs it can cause problems, because it becomes easy to accidentally overwrite variables that you did not intend to change, or to have a script depend on variables that only exist because of something you did earlier at the command line.
Scripts also cannot have their own private workspace. Everything they do touches the base workspace. That is the main difference between a script and a function.
What a Function Is
A function is a piece of code with a defined interface. It has a function signature that specifies input arguments and output arguments. It runs in its own workspace, which is separate from the base workspace.
The first line of a function file defines the function. For example, a simple function that adds two numbers could look like this, saved in a file named addtwo.m:
function c = addtwo(a, b)
c = a + b;
end
Here, addtwo is the function name. The variables a and b are input arguments. The variable c is the output argument. The body of the function is the code between the function line and the end line.
When you call this function from the Command Window or from a script, you write:
result = addtwo(10, 5);
MATLAB creates a separate function workspace that contains a, b, and c. Inside that workspace, a has the value 10 and b has the value 5. The function computes c = 15 and then returns that value to the caller. Only the output that you assign, here result, appears in the caller’s workspace.
The important point is that variables inside a function are local. They do not appear in the base workspace, and they do not see variables from the base workspace unless passed in as inputs. If you have a variable a in the Command Window, and the function uses a parameter named a, those are two different variables that do not interfere with each other.
Workspaces: Script vs Function
The key conceptual difference between scripts and functions is workspace behavior.
When you run a script, MATLAB uses the base workspace. Any assignment like x = 5; directly creates or changes x in that base workspace. Any expression like y = x + 1; uses the current value of x from the base workspace.
When you call a function, MATLAB creates a new workspace for that function call. The input arguments are created in that workspace, and any other variables the function creates or modifies exist only there. When the function finishes, that workspace is discarded. Only the values explicitly returned as outputs are copied back to the caller.
For instance, suppose you have:
x = 10;
y = 20;
result = addtwo(x, y);
Here x and y in the base workspace are passed to the function as inputs. Inside addtwo, MATLAB uses local variables a, b, and c. The calculation inside the function is:
$$c = a + b$$
At the end of the function, MATLAB assigns c to the output result. After the call, the base workspace holds x, y, and result. It does not gain variables called a, b, or c from inside the function.
If you try to access a after the function call, MATLAB will report an undefined variable error, because a only ever existed inside the function workspace.
Creating Script Files
To create a script file in MATLAB, you use the Editor and save the file with a .m extension. Inside the file, you write MATLAB statements just as you would type them in the Command Window, but with no function line.
A minimal script file may contain a short sequence like:
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y)
Assuming this is saved as plotsine.m, you run it by typing plotsine in the Command Window. The script will create the variables x and y in the base workspace and produce a plot.
You can also run scripts from the Editor by pressing the Run button. The effect is the same. All script code runs as if you had copied it into the Command Window and pressed Enter.
Because scripts can be short and informal, they are often used as quick scratch pads, for one time calculations, or to document and rerun a series of interactive commands.
Creating Function Files
To create a function file, you also use the Editor and save the file with a .m extension. However, the first line of the file must start with the keyword function followed by the function declaration.
For example, a function that computes the area of a circle given its radius could be:
function A = circleArea(r)
A = pi * r.^2;
end
You save this as circleArea.m. The file name and the function name must match for this primary function. You then call it from the Command Window or from another script or function:
radius = 3;
area = circleArea(radius)
circleArea runs in its own local workspace. It sees the input argument r. It creates A and returns it. The base workspace receives only area. The function itself does not know or care what variable name the caller uses when it stores the result.
Function declarations can have more than one input or output, but the main idea for this chapter is the presence of a function line and the existence of a separate workspace.
When to Use Scripts
Scripts are best used when you are working interactively, exploring data, or writing simple one off procedures that do not need to be reused in many different contexts.
For example, if you just read some data from a file, clean it, and plot it once for a specific report, you may keep all of those commands in a single script file. The script can assume that certain files exist and that certain paths are set, and you can quickly modify the code and rerun it while you look at results.
Scripts are also convenient for demonstrating or teaching concepts, because the code is executed line by line in the base workspace, and learners can immediately inspect any variable.
Scripts can be helpful for automating a linear workflow, like:
- Load some data.
- Process the data.
- Plot a result.
- Save the plot.
In a script, these steps are just listed one after another. You run the script as a whole and obtain the result.
When to Use Functions
Functions become important as soon as you want to reuse code in different situations or with different inputs, or when you want to organize a larger project.
A function is the right choice when you want to do the same computation many times but with different parameters. Instead of copying and pasting the same block of code into different scripts, you can place that logic in a function and call it wherever needed.
Functions are also preferred when you want to avoid unintended interactions between parts of your code. Since functions do not depend on variables in the base workspace, they are more predictable. You know exactly which values they will use, those given as inputs, and what they will produce, the outputs. This makes functions easier to test and debug.
In larger programs, it is common to use a small script or a main function to drive the overall workflow, and then call several helper functions that each perform a single well defined task. This separates concerns and reduces repeated code.
Converting a Script into a Function
As beginners become more comfortable, it is common to start with scripts and then gradually turn useful scripts into functions. The basic steps to convert a script to a function are straightforward.
First, you need to decide what the inputs to your code should be. Look at any values that are currently hard coded inside the script or that come from the base workspace. For example, if your script contains:
r = 3;
A = pi * r.^2;
and you realize you want to compute the area for many different radii, you can turn this into a function by replacing the fixed variable r with an input argument.
Second, you decide what results should be returned as outputs. In the small example, A is clearly the useful result. So you create a function line that names an output and an input:
function A = circleArea(r)
A = pi * r.^2;
end
Now the code is reusable. Any previous script that used the bare code can instead call circleArea with different values of r.
For a more involved script, the process is the same. Identify the external variables that it uses, pass them in as inputs, and identify which results should be returned. Remove any dependence on variables that live only in the base workspace. Add an appropriate function line and an end statement.
Sometimes you keep a small top level script whose only task is to set parameters and call one or more functions. That script plays the role of a simple driver, while the functions do the detailed work.
Scripts, Functions, and Name Conflicts
Because scripts share the base workspace, it is easy for them to introduce or modify variables that other scripts depend on. Two different scripts might accidentally use the same variable names for very different purposes, which can lead to confusing behavior.
Functions minimize this problem by keeping their variables local. However, there is still the potential for name conflicts between function names and variable names. MATLAB first checks variables in the current workspace, then looks for functions with that name.
For example, suppose you have a function called mean in your path, which MATLAB normally provides as a built in. If you create a variable with the name mean in the base workspace:
mean = 10;
and later you try to call mean(x) to compute an average, MATLAB will attempt to index into the numeric variable mean instead of calling the function. This is a name conflict between a variable and a function. It affects both scripts and functions, but scripts are more likely to accidentally create such conflicts because they continuously add variables to the base workspace.
Using functions encourages you to think carefully about names and inputs, and to return values explicitly. Scripts are useful, but they require more attention to the state of the base workspace to avoid unexpected interactions.
Combining Scripts and Functions
In practice, MATLAB code bases often use both scripts and functions together. A common pattern is to have a simple script that acts as a starting point for a task. That script might:
- Define input values or file names.
- Call one or more functions that perform calculations or produce plots.
- Optionally, do a few quick plotting or saving commands.
Most of the reusable logic lives in functions, while the script simply coordinates and documents the workflow.
Over time, as your work grows more complex or as you share your code with others, you may find that more of your logic moves into functions and that scripts remain only as small drivers or examples.
Important points to remember:
Scripts:
Share the base workspace with the Command Window. Do not have input or output arguments. Are convenient for quick, linear workflows and interactive work.
Functions:
Have a function line with defined inputs and outputs. Run in their own local workspace. Are better for reusable, reliable, and testable code.
When in doubt, start with a script to explore a problem, then turn stable, repeated logic into functions so you can call it safely from many places.