Intro to MATLAB · for EEGLAB lesson 2 / 8

Variables and the Workspace

Give a value a name, and MATLAB keeps it until you clear it.

1Making a variable

A variable is a name with a value stored under it. The = sign means "store", not "equals": read srate = 500 as "srate gets 500". Watch srate appear in the Workspace. Typing the name alone shows its value.

srate = 500
srate

2Using variables

Once a value has a name, you can use the name in calculations.

seconds = 120
nSamples = srate * seconds

MATLAB worked out nSamples once, when you pressed Enter. If you change srate now, nSamples does not update by itself. Run the calculation again to get the new value.

srate = 250
nSamples
nSamples = srate * seconds

3The semicolon

A semicolon at the end of a line tells MATLAB to do the work without printing the result. The variable is still made; it just does not echo.

nChans = 32;
nChans

Scripts end almost every line with a semicolon. A dataset with 32 channels and 30,000 time points holds 960,000 numbers, and you do not want them all printed.

4Naming rules

  • Start with a letter, then use letters, digits, or underscores: sub01, n_trials, nSamples.
  • No spaces and no hyphens. MATLAB reads sub-01 as "sub minus 1".
  • Capitals matter. EEG, eeg, and Eeg are three different names.
  • Do not reuse the name of a function. After mean = 7, mean is a number and the averaging function is hidden until you clear it.
sub-01 = 5
Srate  # capital S: a different name from srate
mean = 7
mean([1 2 3])  # MATLAB now reads this as indexing into the number 7
clear mean
mean([1 2 3])

5Seeing and clearing the Workspace

who lists your variables. whos adds the size, memory, and class of each. clear name removes one variable; clear on its own removes them all.

who
whos
clear seconds
clear

Do not mix up clc and clear. clc cleans the screen and keeps your variables. clear deletes the variables and leaves the screen alone.

In EEGLAB. EEGLAB keeps the dataset you are working on in a variable called EEG, and all loaded datasets in ALLEEG. clear removes them from memory, not from your disk. Lab scripts often start with clear so nothing left over from an earlier session sneaks into the analysis.

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/