Intro to MATLAB · for EEGLAB lesson 5 / 8

Arrays and Matrices

One name holds many numbers, counted from 1.

1Row and column vectors

Square brackets make an array. Spaces or commas separate numbers along a row; a semicolon starts a new row.

amps = [4.2 3.9 5.1 4.8]
col = [1; 2; 3]
size(amps)
size(col)

size always answers rows first, then columns.

2Counting from 1

Parentheses pick elements out of an array. MATLAB counts from 1, and end means the last one.

amps(1)
amps(end)
amps(2:3)
amps(0)
amps(5)

There is no element 0, and asking past the end is an error that tells you how many elements there are.

3The colon operator

start:step:stop counts from start to stop. Leave out the step and it counts by 1. It is the quick way to make a time axis.

1:5
0:0.25:1
t = 0:0.002:1;  # one second of time points at 500 Hz
numel(t)
t(1:4)

At 500 Hz a sample comes every 2 ms, so one second from 0 to 1 holds 501 time points: 500 steps plus the starting point.

4Matrices: rows and columns

A matrix has rows and columns. Index it with two numbers, row first. A colon on its own means "all of them".

A = [1 2 3; 4 5 6]
A(2, 3)
A(1, :)
A(:, 2)
size(A)

5EEG data is a matrix

EEG is stored as a matrix with one row per channel and one column per time point. Here is a pretend dataset with 4 channels and 10 time points of random numbers:

data = rand(4, 10)
data(2, :)  # channel 2, every time point
data(:, 1:5)  # every channel, the first five time points
mean(data, 2)  # one average per channel
mean(data)  # one average per time point

The second input to mean picks the direction. mean(data, 2) averages across columns, giving one number per channel. mean(data) on its own averages down each column, giving one number per time point, which answers a different question.

6Math on whole arrays

Math with a single number applies to every element. To combine two arrays element by element, put a dot in front of the operator: .*, ./, .^. Without the dot, * is matrix multiplication from linear algebra, which needs matching inner sizes.

amps * 2
amps .^ 2
A * A
A .* A
In EEGLAB. EEG.data is this kind of matrix. EEG.data(14, :) is channel 14 across the whole recording, and mean(EEG.data, 2) gives one average per channel. The next lesson does this on a loaded dataset.

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/