Scripts and Code Sections
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
Written against MATLAB R2026b. The sessions below were run in GNU Octave 11.3.0 (MATLAB code that Octave also accepts) and show Octave’s output. The Editor commands, the matlab -batch option and the behaviour of local functions in scripts are not available in Octave and are checked against the R2026b documentation ("not run here"). The release in which each feature arrived is given where the documentation states it.
A script is a file of MATLAB commands, saved with the extension .m, that runs exactly as if you had typed its lines at the command prompt. It is the simplest kind of code file: it takes no input arguments and returns no output arguments. This page covers how scripts work and how to run them, how to divide them into sections, how to add functions to them and when a script should become a function (see Functions). Live scripts, which are a different file format with output and formatted text, are on Live Scripts and the Live Editor.
Scripts and the base workspace
The key property of a script is where its variables live. A script reads and creates variables in the base workspace, the same workspace as your interactive session, and shares it with other scripts. When the script finishes, its variables stay; you can list them with whos. A function, by contrast, has its own workspace (see Workspaces, Scope, Global and Persistent Variables).
This is convenient (results are there to inspect) and risky (a script can silently overwrite or depend on something that happens to be in the workspace, and two scripts that use the same variable name collide). The session below creates a script with two sections that sets alpha, n, T and total, then runs it from another file after defining x.
%% Setup
alpha = 1e-4;
n = 5;
%% Compute
T = zeros(n);
total = sum(T(:));
clear
x = 1;
run("myscript.m")
names = sort(who);
disp(strjoin(names', " "))
disp(exist("alpha", "var"))
Octave 11.3.0 output:
T alpha n total x
1
The five names include x, which was defined before the script ran, so the script could have read or changed it; the script’s own alpha, n, T and total are afterwards in the calling workspace, and exist("alpha", "var") is 1.
Creating and running a script
Create a script in the Editor with the New Script button on the Home tab, or with the edit function: edit new_file_name creates the file if it does not exist and opens it. Save the file in the current folder or on the search path (see Search Path, Startup and Files). A script file name follows the variable name rules, so it must start with a letter and contain letters, digits and underscores, and must not shadow a function you want to keep (a file named sum.m hides the built-in sum).
Ways to run a script, from the documentation:
| Way | What it does |
|---|---|
Type the script name and press Enter |
Runs the script in the base workspace. Do not type the extension. Works when the file is in the current folder or on the path. |
The Run button on the Editor tab |
Runs the script. Many installations bind it to F5; check your keymap. |
|
Runs a script by name, or by a full or relative path when the file is not on the path or in the current folder. The documentation says the script can access variables of the current workspace. |
A line with the script name inside another script or function |
|
|
Runs MATLAB non-interactively: no desktop, no splash screen, text logged to standard output and standard error, and an exit code of 0 if the statement ran without error, non-zero otherwise. Give the name without extension, with the file on the path or in the startup folder. Not run here. |
run accepts a string scalar or a character vector, and the documentation notes that it works for any file type MATLAB can execute. The -batch option is for scripting and continuous-integration workflows (the Linux and Windows pages of the matlab command document it, and the batchStartupOptionUsed function tells a script whether it is running that way); it throws an error if the code opens a dialog that waits for user input. Do not combine it with -r, the older interactive form. The heatflow run script, matlab -batch "runHeatflow", is the form later pages use for automation.
matlab -batch "runHeatflow"
Not run here (needs a MATLAB installation); the command and the exit-code rule are as documented for matlab on the desktop platforms.
Code sections with %%
A section is a block of a code file that you can run on its own. A line that starts with two percent signs, %%, begins a new section; the text on that line is the section title. The title is optional, but it makes the file easier to navigate and appears as a heading if you publish the file. The Editor highlights the selected section, and also offers a Section Break button on the Editor tab. To delete a section break, delete the two percent signs.
The commands, from the documentation:
| Operation | Editor tab, Section group |
|---|---|
Run all the code in the file |
Run (Run group) |
Run the selected section |
Run Section |
Run the selected section, then move to the next |
Run and Advance |
Run the selected section and all after it |
Run to End |
Run to a specific line and pause |
Run to Here button in the margin (saved code only in the Editor) |
A section can be run individually only if it holds the values it needs, or those values already exist in the workspace. Running a section does not save the file, and the file need not be on the search path. For .m files, Run Section requires R2017b or later according to the local-functions page; when you rerun one section repeatedly (for example, to tune the stability factor of the heatflow time step), run the earlier sections once first so their variables exist.
Related features from the documentation: navigate between sections with Go To, Previous Section or Next Section (Ctrl+Up and Ctrl+Down); since R2023a the Editor can increment, decrement, multiply or divide a numeric value inside a section and rerun it after every change (right-click the value and choose Increment Value and Run Section); and the Editor adds section breaks itself around a function declaration and its end, and inside loops and conditionals, in ways you cannot remove. Sections are also used by the Publish feature and by live scripts.
A heatflow script written in sections follows the stages of the simulation and is the form the tests and the build use later:
%% Parameters
alpha = 1e-4;
n = 21;
dx = 1/(n-1);
dt = 0.2*dx^2/alpha;
assert(dt <= dx^2/(4*alpha))
%% Initial condition
T = zeros(n,n);
T(:,1) = 100;
%% Time stepping
tol = 1e-6;
maxSteps = 20000;
step = 0;
delta = Inf;
while delta > tol && step < maxSteps
step = step + 1;
Tn = T;
Tn(2:end-1,2:end-1) = T(2:end-1,2:end-1) + alpha*dt/dx^2 * ...
(T(1:end-2,2:end-1) + T(3:end,2:end-1) ...
+ T(2:end-1,1:end-2) + T(2:end-1,3:end) ...
- 4*T(2:end-1,2:end-1));
delta = max(abs(Tn(:) - T(:)));
T = Tn;
end
%% Report
fprintf("converged after %d steps, T center %.4f\n", step, T(11,11));
The loop in this script is explained, with its flowchart, on Control Flow. Run in Octave 11.3.0 (sections are plain comments there), it prints converged after 1304 steps, T center 24.9999. The sections have no effect on the result: %% is a comment to the interpreter and is meaningful only to the Editor.
Local functions in scripts
A script can define functions, called local functions. They let you reuse code inside one script without creating and managing separate function files, and they are handy for experiments because they are easy to add and change. The rules from the documentation:
-
Each local function starts with its own
functionline and ends withend. -
Before R2024a local functions in a script had to be defined at the end of the file, after the last line of script code. Since R2024a they can appear in any order and anywhere in the script, with one limit: the file must not begin with a
functionline, because a file whose first code line is a function declaration is a function file, not a script. Local functions in scripts themselves arrived in R2016b. -
A script that contains local functions must contain executable code outside any function.
-
Local functions are visible only in their own file. They cannot be called from the Command Window or from functions in other files; such a call fails with the error identifier
MATLAB:UndefinedFunction("Unrecognized function or variable"; not run here). -
They have precedence over functions of the same name in other files (see Function Precedence and Name Resolution).
-
They have their own workspaces and do not see the script’s variables or the base workspace unless you pass them as arguments.
-
Their help is available with
help scriptname>functionname, for examplehelp mystats>mymean. -
To run a script with local functions, use the Run button or type the script name. In live scripts you can run only the sections that come before the local function definitions.
% heatflowStats.m: a script with a local function
T = [20 25 30; 22 27 33];
avg = rowMean(T);
disp(avg)
function m = rowMean(A)
% ROWMEAN Mean of each row.
m = sum(A,2)/size(A,2);
end
This script defines the function after the code that uses it, which is the form allowed since R2024a and also the pre-R2024a form (end of file). It is not run here: Octave requires a function to be defined before it is used in a script, and the file layout above is MATLAB’s. Checked against the R2026b documentation of local functions in scripts.
Scripts versus functions
Scripts store commands exactly as you would type them. Functions are more flexible and more easily extended: they take inputs and return outputs, so one function serves many calls, and they have their own workspace. The documentation illustrates it with a triangle area. As a script, triarea.m sets b and h and stores the result in a in the base workspace; to calculate another triangle you edit the script and rerun it. As a function the declaration replaces the assignments:
function a = triarea(b,h)
a = 0.5*(b.*h);
end
Calls such as a1 = triarea(1,5), a2 = triarea(2,10) and a3 = triarea(3,6) do not overwrite a variable a in the base workspace, because the function’s a is local; the results go to a1, a2 and a3 (2.5, 10 and 9 per the documentation). The same rule shows in Octave: a variable defined inside a function does not exist in the caller.
clear
a = 1;
function r = f(a)
tmp = a*2;
r = tmp + 1;
end
y = f(3);
disp(a)
disp(y)
disp(exist("tmp", "var"))
Octave 11.3.0 output:
1
7
0
The base-workspace a is untouched, f(3) returned 7, and the function’s tmp does not exist outside it. The function is defined between script statements, a layout MATLAB accepts since R2024a (it would have to move to the end of the file for earlier releases); the file still starts with script code, as it must.
When to keep a script: a short, linear sequence you run for its side effects, such as setting up the path or producing a report; an exploration you will rerun by hand; the top level of an analysis that calls functions. When to turn it into a function:
-
you change constants by editing the file before each run (make them inputs);
-
the script is used from other scripts, or the results are used by other code (make them outputs);
-
variable names collide with those in the workspace, or you need
clearat the top to be safe; -
it exceeds a screen or two, or repeats a block (extract the block into a local function);
-
you want to test it (tests call functions with arguments and compare outputs; see Unit Testing with matlab.unittest).
For heatflow, the time-stepping script above would become a function heatflow.simulate(plate, dt, tol) once the class and namespace pages introduce them; the script remains useful as the quick driver that calls it.
Pitfalls
-
Shared workspace. A script sees and changes everything in the base workspace. A name that exists from an earlier session (
n,T,step) can change a result silently; initialise what you use, and prefer a function for anything reused. -
clear allat the top removes functions and breakpoints from memory and slows the next run;clearorclearvarsis usually enough (see Workspace Variables and MAT-Files). -
Name clashes. A script named like a function or a variable shadows or is shadowed. Avoid names such as
test.m,sum.m,plot.morheatflow.m(which would also hide the namespace+heatflowin confusing ways); check withwhich name. -
Typing the extension. Run
myscript, notmyscript.m. -
Running a section out of order when it needs variables from an earlier one: it fails with the error identifier
MATLAB:UndefinedFunction(the message is "Unrecognized function or variable" followed by the name; not run here), or worse, uses stale values from a previous run. -
Local functions in scripts before R2024a placed in the middle of the file: not supported in older releases; put them at the end for code that must run there.
-
returnin a script ends the script (and, if it was called by another script or function, returns to it). -
%%is two percent signs at the start of the line. A section title follows on the same line; text after a single%is an ordinary comment.
Where older books differ
Older books present scripts as the main way to write programs and treat the Editor as a place to save command lists. That is still valid, but they predate several features documented above: the increment commands for sections (R2023a), local functions anywhere in a script (R2024a; before that only at the end of the file) and live scripts. Running a file by typing its name, which they teach, is still the basic form. The advice they give to put reusable code in function files stands, with a modern addition: use argument validation in functions (see Argument Validation). Code in older books often starts every script with clear all, which current practice discourages.