Minimal Coding: PCA in Just Three Lines of MATLAB Code

Computer code is becoming increasingly complex, making it difficult for beginners to understand. Minimal coding offers a possible solution. Here is an example of minimal code for a principal component analysis.

The PCA code from the Statistics and Machine Learning Toolbox in the current version of MATLAB R2026a is 423 lines long, including comment lines. That is a lot compared to a method that actually involves only three steps to linearly decompose a dataset with n variables: (1) the data is mean-centered, (2) the covariance matrix is computed, and (3) the n eigenvectors of the covariance matrix are computed—that’s it. The eigenvectors are the n new variables, also known as n principal components (PCs). The problem with this is that beginners read about these three steps in textbooks—usually expressed in mathematical formulas—and then end up using PCA as a black box, even though the PCA code in MATLAB is open-source. It’s no different in Python; there, too, the code is several hundred lines long.

Here is an example of minimal coding—that is, reducing computer code to the absolute minimum. First, we generate a dataset with only n=2 variables that are linearly correlated. The goal of PCA is to decompose this dataset linearly—that is, to replace the two variables with two new variables, the principal components, which are completely linearly decorrelated, provided the data are normally distributed. If they are not, PCA can only decompose the data incompletely.

clear, clc, close all
rng(0)
data(:,1) = randn(30,1);
data(:,2) = 3.4 + 1.2*data(:,1);
data(:,2) = data(:,2) + 0.2*randn(30,1);

Here are the three steps described above, mean centering, calculating the covariance matrix, and calculating the eigenvectors together with the associated eigenvalues:

data = data-mean(data);
C = cov(data);
[V,D] = eig(C);

Essentially, that’s it—a classic three-step principal component analysis. The eigenvectors are the principal components, and the eigenvalues contain information about the proportion of the dataset’s information content (variance) that is explained by the principal components. Nowadays, singular value decomposition is used instead of eigenvector calculation; this is a related method for calculating principal components that yields largely identical PCs but offers the advantage of fewer rounding errors, greater algorithm stability, and the ability to avoid calculating large covariance matrices for large datasets. There are many things you can do with these results, as described in the post “PCA in Six Steps,” which is available for both Python and MATLAB, as well as in the two books listed below, which are also available for both MATLAB and Python. For example, you can convert the coordinates of the data points in the new coordinate system from PC1 and PC2:

ndata = data*V;

In addition, the data can be plotted in the old coordinate system (with a strong linear relationship between x and y) and in the new coordinate system (without a linear correlation between PC1 and PC2):

subplot(2,1,1)
plot(data(:,1),data(:,2),'*')
xlabel('x'),ylabel('y')

subplot(2,1,2)
plot(ndata(:,2),ndata(:,1),'*')
xlabel('PC1'),ylabel('PC2')

If you would like to make it look a little nicer, I recommend this slightly more extensive code, which consistently uses graphic attributes according to the name-value scheme:

figure('Position',[100 800 800 600],...
   'Color',[1 1 1])
axes('Position',[0.1 0.6 0.8 0.3],...
   'Xlim',[-4 4],...
   'YLim',[-5 5],...
   'FontSize',12), hold on
line(data(:,2),data(:,1),...
   'LineStyle','None',...
   'Marker','o',...
   'MarkerSize',8,...
   'MarkerFaceColor',[0.1 0.3 0.8])
xlabel('x'),ylabel('y')
axes('Position',[0.1 0.2 0.8 0.3],...
   'Xlim',[-5 5 ],...
   'YLim',[-0.5 0.5],...
   'FontSize',12), hold on
line(ndata(:,2),ndata(:,1),...
   'LineStyle','None',...
   'Marker','o',...
   'MarkerSize',8,...
   'MarkerFaceColor',[0.1 0.3 0.8])
xlabel('PC1'),ylabel('PC2')

The code above corresponds to the brief description of PCA found in textbooks. The much more comprehensive code for MATLAB and Python naturally offers a great many more options—for example, you can switch between the eigenvector and singular value decomposition methods, and much more—but this significantly increases the effort required to learn it.

For over 30 years, I have been striving to keep the code as simple as possible—not only to make it easier for students to understand, but also to facilitate collaborative coding. In my textbooks and my courses, I consistently follow this principle: algorithms are first reduced to a handful of lines of code, as shown above, before a ready-made function—such as PCA in a MATLAB toolbox or a Python package—is used to handle the routine tasks.

References

Trauth, M.H. (2025) MATLAB Recipes for Earth Sciences – Sixth Edition. Springer International Publishing, 567 p, https://doi.org/10.1007/978-3-031-57949-3.

Trauth, M.H. (2024) Python Recipes for Earth Sciences – Second Edition. Springer International Publishing, 491 p., https://doi.org/10.1007/978-3-031-56906-7.