Intro to MATLAB · for EEGLAB lesson 7 / 8

Functions

Inputs go in the parentheses; outputs come back on the left.

1Calling a function

A function takes inputs in parentheses and hands back an output. Without a name on the left, the output goes to ans.

x = [4 8 15 16 23 42];
mean(x)
avg = mean(x)
round(3.14159, 2)

2More than one output

Some functions return several outputs. Ask for them with square brackets on the left, in the order the function gives them.

[biggest, where] = max(x)
[nChans, nPoints] = size(rand(32, 1000))

3Reading the help

help followed by a function name prints a short description of the inputs and outputs. The full MATLAB documentation has a page for every function, with examples.

help mean
help round

4EEGLAB functions take the dataset in and give it back

Most EEGLAB processing functions start with pop_. They take the dataset as their first input and return the changed dataset. Options come as name and value pairs: 'locutoff', 0.1 means "set the low cutoff to 0.1 Hz".

EEG = pop_loadset('filename', 'sub-01.set', 'filepath', 'data');
EEG = pop_eegfiltnew(EEG, 'locutoff', 0.1, 'hicutoff', 30);

The EEG inside the parentheses is the dataset going in. The EEG = on the left stores the result under the same name, replacing the old one.

5The missing EEG =

Leave out EEG = and the result goes to ans. EEG itself does not change, and nothing warns you, which makes this one of the most common mistakes in EEGLAB scripts. pop_select keeps only some channels, so its effect is easy to see:

pop_select(EEG, 'channel', 1:10);
EEG.nbchan  # still 32: the smaller dataset went to ans
EEG = pop_select(EEG, 'channel', 1:10);
EEG.nbchan

6Writing your own function

The Editor shows secondsToSamples.m, a function file in the psych390 folder. Its first line says what comes out (n), what it is called, and what goes in (sec and srate). The comment lines under it become its help. The file name must match the function name.

n = secondsToSamples(2, 500)
help secondsToSamples
which secondsToSamples

Inside the function, sec and srate live in the function's own workspace, so they never show up in yours. Like any function, it has to be in the current folder or on the path:

cd ..
secondsToSamples(2, 500)
cd psych390

Now change the function in the Editor, for example to return milliseconds with n = sec * 1000;, press Save, and call it again.

Your turn

Each box ticks itself when you do it in the practice window. Stuck? "show me" puts a command in the window for you.

References

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