% The EEG data by default is recorded with reference to the hardware reference, which is Pz.
% This means that there was not a Pz channel in the recording file.
% We have to do some simple math to re-reference the data and reconstruct the Pz channel.
%
% In this code, we are conducteding re-referencing for the EEG singnal with respect to Vref.
% Vref is the average between the electrodes A1 and A2
clc
clear
close all
warning off
for s=1:59 %number of subject
Name = 'S%d_0.5_raw.csv'; %Change between speeds 0.5, 0.75, and 1.
filename = sprintf(Name,s);
A=readmatrix(filename, 'HeaderLines', 16); %ignore the first 16 rows (trial description)
LE=(A(:,11)+A(:,23))/2; %Linked Ears = average of A1 and A2
Pz=zeros(height(A), 1); %Generate Pz channel with reference to Pz
A(:,10)=Pz; %Explaination: Replace Pz in A instead of CM channel
channels=[2:10,12:17,20,21,24,25]; %the 19 EEG channels
A1=A(:,channels); %P3,C3,F3,Fz,F4,C4,P4,Cz,Pz,Fp1,Fp2,T3,T5,O1,O2,F7,F8,T6,T4
%Rearrange channels to match EEGLAB and the default order as follows
% 1 Fp1
A11(:,1)=A1(:,10);
% 2 Fp2
A11(:,2)=A1(:,11);
% 3 F7
A11(:,3)=A1(:,16);
% 4 F3
A11(:,4)=A1(:,3);
% 5 Fz
A11(:,5)=A1(:,4);
% 6 F4
A11(:,6)=A1(:,5);
% 7 F8
A11(:,7)=A1(:,17);
% 8 T7 (T3)
A11(:,8)=A1(:,12);
% 9 C3
A11(:,9)=A1(:,2);
% 10 Cz
A11(:,10)=A1(:,8);
% 11 C4
A11(:,11)=A1(:,6);
% 12 T8 (T4)
A11(:,12)=A1(:,19);
% 13 P7 (T5)
A11(:,13)=A1(:,13);
% 14 P3
A11(:,14)=A1(:,1);
% 15 Pz
A11(:,15)=A1(:,9);
% 16 P4
A11(:,16)=A1(:,7);
% 17 P8 (T6)
A11(:,17)=A1(:,18);
% 18 O1
A11(:,18)=A1(:,14);
% 19 O2
A11(:,19)=A1(:,15);
for ch=1:19 %Referencing the 19 EEG channels with respect to LE ... F1-LE, F2-LE,,,,,
A_ref(s, 1, ch, :)=A11(:,ch)-LE; %Change between index 1,2,3 for the three speeds 0.5,0.75,1
% ... A_ref: subjects(59), Speeds(3), Channels(19), Samples(17960)
end
end
%.......................................%