├── README.md ├── f_CSP.m └── main_CSP.m /README.md: -------------------------------------------------------------------------------- 1 | # Common-Spatial-Pattern-Algorithm 2 | Common spatial pattern (CSP) is a mathematical procedure used in signal processing for separating a multivariate signal into additive subcomponents which have maximum differences in variance between two windows. This algorithm is mainly used in motor imagery based BCI for processing EEG data. 3 | -------------------------------------------------------------------------------- /f_CSP.m: -------------------------------------------------------------------------------- 1 | function [result] = f_CSP(varargin) 2 | % This code is for calulating the projection matrix for CSP 3 | % Haider Raza, Intelligent System Research Center, University of Ulster, Northern Ireland, UK. 4 | % Raza-H@email.ulster.ac.uk 5 | % Date: 03-Oct-2014 6 | 7 | % Input: 8 | 9 | % left: left hand data 10 | % right: right hand data 11 | % 12 | % Output: 13 | % left: Left hand data 14 | % right: right hand data 15 | 16 | if (nargin ~= 2) 17 | disp('Must have 2 classes for CSP!') 18 | end 19 | 20 | Rsum=0; 21 | %finding the covariance of each class and composite covariance 22 | for i = 1:nargin 23 | %mean here? 24 | R{i} = ((varargin{i}*varargin{i}')/trace(varargin{i}*varargin{i}'));%instantiate me before the loop! 25 | %Ramoser equation (2) 26 | Rsum=Rsum+R{i}; 27 | end 28 | 29 | % Find Eigenvalues and Eigenvectors of RC 30 | % Sort eigenvalues in descending order 31 | [EVecsum,EValsum] = eig(Rsum); 32 | [EValsum,ind] = sort(diag(EValsum),'descend'); 33 | EVecsum = EVecsum(:,ind); 34 | 35 | % Find Whitening Transformation Matrix - Ramoser Equation (3) 36 | W = sqrt(inv(diag(EValsum))) * EVecsum'; 37 | 38 | 39 | for k = 1:nargin 40 | S{k} = W * R{k} * W'; % Whiten Data Using Whiting Transform - Ramoser Equation (4) 41 | end 42 | 43 | %generalized eigenvectors/values 44 | [B,D] = eig(S{1},S{2}); 45 | % Simultanous diagonalization 46 | % Should be equivalent to [B,D]=eig(S{1}); 47 | 48 | [D,ind]=sort(diag(D));B=B(:,ind); 49 | 50 | %Resulting Projection Matrix-these are the spatial filter coefficients 51 | result = B'*W; 52 | end 53 | -------------------------------------------------------------------------------- /main_CSP.m: -------------------------------------------------------------------------------- 1 | % Call the CSP function using the left and right hand data 2 | % Input 3 | % C1_Data=Class 1 Data in Channels*Observations 4 | % C2_Data=Class 2 Data in Channels*Observations 5 | 6 | 7 | % Output: 8 | % W=Channels*Channels % Projection Matrix 9 | 10 | [W] = f_CSP(C1_Data,C2_Data); 11 | --------------------------------------------------------------------------------