Write the steps once and let a loop run them for every participant.
A for loop runs the lines between for and end once for each value. On a single line, separate the parts with commas.
for i = 1:3, disp(i), end
for i = 1:3
fprintf('Participant %d\n', i);
end
Each time around, i takes the next value: 1, then 2, then 3. The indenting is for the reader; MATLAB goes by for and end.
Put the sprintf template from lesson 4 inside a loop and you get every file name.
for s = 1:3
fname = sprintf('sub-%02d.set', s);
disp(fname)
end
When participant IDs do not follow a pattern, keep them in a cell array, made with curly braces. A cell array can hold text of different lengths side by side.
subjects = {'sub-01', 'sub-02', 'sub-03'}
subjects{2}
subjects(2)
numel(subjects)
Braces take the text out: subjects{2} is 'sub-02'. Parentheses give back a smaller cell array, {'sub-02'}, which EEGLAB will not accept as a file name.
for s = 1:numel(subjects)
fprintf('Next up: %s\n', subjects{s});
end
if runs lines only when a condition is true, and else handles the rest. Here the loop checks each file and skips the ones that are missing.
for s = 1:4
fname = sprintf('sub-%02d.set', s);
if isfile(fullfile('data', fname))
fprintf('%s found\n', fname);
else
fprintf('%s is missing, skipping it\n', fname);
end
end
A script is a file of commands that runs from top to bottom when you press Run or type its name. The Editor holds process_all.m. It loads each participant, filters the data, and saves a copy with _filt added to the name. Read it, press Run, and watch new files appear in the Current Folder (open data).
process_all ls data
In the Editor, change 'sub-03' to 'sub-3', press Run, and read the message. It names the file MATLAB could not find and the line of the script where it stopped. Every line before that one already ran, so sub-01 and sub-02 were filtered and saved. Put the name back, and run it again.
Each box ticks itself when you do it in the practice window. Stuck? "show me" puts a command in the window for you.
The MathWorks, Inc. (2025). MATLAB documentation. https://www.mathworks.com/help/matlab/
Delorme, A., & Makeig, S. (2004). EEGLAB: An open source toolbox for analysis of single-trial EEG dynamics including independent component analysis. Journal of Neuroscience Methods, 134(1), 9 to 21. https://doi.org/10.1016/j.jneumeth.2003.10.009
Luck, S. J. (2022). Applied event-related potential data analysis. LibreTexts. https://doi.org/10.18115/D5QG92