Table of Contents
Why Section Your Code
When MATLAB programs grow beyond a few lines, it quickly becomes uncomfortable to run everything from top to bottom every time you make a small change. Code sections allow you to split a script into smaller, logical blocks that you can run independently. This is especially helpful during exploration, debugging, and teaching, because you can focus on one part of the script at a time.
Sections work in both regular scripts and live scripts, but the way they look and how you interact with them has some differences. In both cases, the idea is the same: divide your script into chunks and run each chunk without running the entire file.
Creating Sections in a Script
In a plain .m script, MATLAB identifies a section by special comment lines. The standard and most reliable way to start a new section is with a line that begins with two percent signs:
%% Data loading
data = load("measurements.mat");
%% Preprocessing
cleanData = data.x(data.x > 0);
%% Plotting
plot(cleanData);
Each line that starts with %% begins a new section. Everything from that section header down to the next %% line (or the end of the file) belongs to that section.
You can write text after the %%. This text becomes the section title that appears in the Editor and in the automatic navigation list. Choose brief, descriptive titles so you can quickly find the part of the script you need.
Section headers must begin at the start of the line. Putting spaces before %% can prevent MATLAB from recognizing the line as a section separator. The %% must be in a comment, so do not write code on the same line.
You can also create a new section from the Editor without typing the %% yourself, depending on your MATLAB version and layout. There are “Section” related buttons in the Editor tab that can insert a section break at the current cursor position. Even when you use these buttons, MATLAB simply inserts the %% line for you.
Recognizing Sections in the Editor
Once you add %% section headers, MATLAB shows visual dividers in the Editor. Each section gets a slightly shaded background with its header at the top. The section headers may appear in bold, and in many layouts you also see a list of sections in the “Go To” or “Navigate” controls.
These visual clues make it clear where one section ends and the next begins. They also provide quick navigation. You can click inside any section and run only that part of the script, without scrolling or manually selecting code.
If you see that your script appears as one continuous block, check whether you have used %% correctly, starting at the first column, and that the file is saved as a script, not a function. Sections do not split inside a function definition in the same way they do in a script.
Running the Current Section
The most common way to use sections is to run only the section where your cursor is. Place the text cursor anywhere inside a section, then use the appropriate Editor command.
In most MATLAB installations there is a “Run Section” button in the Editor tab. Clicking this button executes only the code in the current section. MATLAB evaluates the lines in that section as if they were at the command line, in order, and any variables created or modified appear in the base workspace.
You can usually use a keyboard shortcut to run the current section. In many defaults this is Ctrl+Enter (Windows) or Command+Enter (macOS). If this does not work, check the tooltip over the “Run Section” button or your MATLAB preferences to see the current shortcut.
When you run a section, MATLAB does not automatically run the sections above or below it. This is powerful but can also be confusing. If the current section depends on variables that should have been created in earlier sections, and you have not run those earlier sections yet in this session, you may see errors that a variable does not exist. In practice, this means that you often need to run earlier sections when you start a fresh session, and only then run later sections individually.
Running Sections and Managing State
Code sections in a script share the same base workspace. If you create a variable in the first section and then run the second section, the second section can see and use that variable, as long as it has not been cleared. This makes it easy to build up a sequence like “load data,” “clean data,” “analyze data,” and “plot results,” each in its own section.
Because everything shares one workspace, the order in which you run sections matters. If a later section assumes a variable exists and you have not run the earlier section that defines it, you get an error. If you edit a section that defines a variable, you may need to re-run that section before running dependent sections again.
You can also re-run the same section many times in a row. This is useful when you are tuning parameters. For example, you might have a “Plotting” section that uses variables already computed. You can change plot options, then press “Run Section” repeatedly to see how the figure changes, without reloading or recomputing everything above.
Clearing variables affects all sections because the workspace is shared. If you put a clear or clearvars command inside a section and run it, variables defined in other sections will disappear unless you are selective. Be deliberate about where you place clearing commands if you plan to run individual sections repeatedly.
Running to a Section and Shortcuts
MATLAB typically provides variations on running sections, such as “Run and Advance,” which runs the current section and then automatically moves the cursor to the next section. This is convenient when you want to step through your script section by section in order, without manually clicking in each section.
In many configurations the Editor has options like “Run to Cursor” or similar tools that execute all code from the beginning of the script up to the line where the cursor is, which may cross section boundaries. These tools use sections as visual markers but focus more on line position rather than section boundaries.
You can also run a selection of lines manually by highlighting them and pressing the regular “Run” button or pressing F9 (Windows default) or the equivalent on macOS. This is not exactly the same as running a section, but sometimes you can use it together with sections when you want to test only part of a section.
Sections in Live Scripts
Live scripts use the same logical idea of sections, but the presentation is richer. A live script file has the extension .mlx instead of .m, and each section appears as a separate block that can contain code, formatted text, equations, and outputs.
In a live script, each section still starts with a %% line, which defines the section title. MATLAB displays these as collapsible blocks. You can click a section header to collapse or expand it. A collapsed section hides its code and outputs, which helps keep a long document readable.
In live scripts, you typically see “Run Section” and “Run All” buttons on each section. Clicking “Run Section” runs only that block and immediately displays its output below the code in that section. “Run All” runs all sections in order, from top to bottom. The workspace behavior is the same: all sections in a live script share the same base workspace, unless you are using special tools such as live functions, which belong elsewhere.
You can insert new sections in a live script from the toolstrip, usually with an “Insert Section Break” command. MATLAB adds a new %% line and creates a new section for you. You can then type a title after the %% and continue with code or narrative.
Typical Section Structure in Practice
In practice, a well structured script might have sections for high level tasks, for example:
%% Setup
% Paths, parameters, and initial settings
addpath("functions");
samplingRate = 1000;
%% Load data
raw = load("datafile.mat");
%% Preprocess
filtered = myFilter(raw.signal, samplingRate);
%% Analysis
results = myAnalysis(filtered);
%% Visualization
plotResults(results);Sections like this let you run the “Setup” and “Load data” sections once at the start of a session. After that, while you develop and debug the “Preprocess,” “Analysis,” or “Visualization” parts, you can repeatedly run only the relevant section instead of the entire file.
When working in a live script, you might extend each of these sections with explanatory text and equations before or after the code block. Each section then becomes both documentation and executable code.
Common Pitfalls When Using Sections
Although sections are helpful, beginners often fall into similar patterns that cause confusion. One common issue is forgetting that a section depends on variables defined earlier in the script. If you open a script, run a later section first, and get “undefined variable” errors, that usually means you need to run the earlier sections that produce those variables.
Another issue is mixing heavy computation with quick experimentation in the same section. If your “Preprocess” section takes several minutes to run, and you need to tweak a minor plotting setting that depends on the output, it may be worth splitting the code further. Place slow, stable parts in their own sections, and faster, experimental code in separate sections or at the end of the script. That way, you can rerun only what you need.
Sections and functions behave differently. Inside a function file, section headers help with navigation but do not create separate workspaces that you can run independently in the same way as script sections. For isolated, reusable logic, functions are more appropriate. For exploratory work and analysis sequences, script sections are usually more convenient.
Finally, remember that MATLAB only recognizes section headers once the file is saved or has been parsed. If you add new %% lines and do not see the section structure update, save the file, or click away and back to the Editor to refresh.
Important points to remember:
Sections in scripts and live scripts begin with a line that starts with %%, which defines the start of a new section and its title.
You can run only the current section from the Editor, usually with a “Run Section” button or a keyboard shortcut, without executing the whole script.
All sections in a script or live script share the same base workspace, so the order in which you run sections matters for variable availability.
Live scripts display sections as separate blocks with code, formatted text, and output, but they follow the same sectioning rule using %%.