% MATLAB code for Principal Component (EOF) Analysis

% Written by Steven Greybush for AOSC 630



% begin from a dataset that has been formatted as follows:

% each row contains K points in space (a spatial pattern / map / vector)

% each column contains information from N different times



% this example is from AOSC 630 Lecture 14

dataset = [1 1.; 0 -1; -1 0]



% N points in time, K points in space

[N K] = size(X);



disp([num2str(K) ' directions in space, ' num2str(N) ' directions in time.']);



% remove the mean from the dataset

X = dataset - mean(mean(dataset));



% covariance matrix in space

disp('Covariance matrix in space:')

S = 1/N * X' * X



% eigenvalue decomposition of the covariance matrix



[eigenvectors, D] = eig(S);

eigenvalues = diag(D);



% can sort the eigenvalues in descending order

% so that the first EOF explains most of the variance



[eigenvalues_sorted,sort_order] = sort(eigenvalues,1,'descend');

eigenvectors_sorted = eigenvectors(sort_order,sort_order);



% eigenvectors = pattern vectors = empirical orthogonal functions (EOFs)

% eigenvalues = principal components (PCs) = amplitudes

eigenvectors_sorted

eigenvalues_sorted



% explain the total variance



total_variance = sum(eigenvalues);



% explain the variance of each EOF



for i=1:min(N,K)

    cumulative_variance = sum(eigenvalues_sorted(1:i)/total_variance)*100;

    disp(['EOF ' num2str(i) ' explains ' num2str(eigenvalues_sorted(i)/total_variance*100) '% of the variance in the dataset.']);

end





