Principal Component Analysis (PCA) in MATLAB - Time & Space Complexity
We want to understand how the time needed to run PCA changes as the data size grows.
How does the work increase when we add more data points or features?
Analyze the time complexity of the following PCA code snippet.
% X is data matrix with n samples and d features
X_centered = X - mean(X);
C = (X_centered' * X_centered) / (size(X,1) - 1);
[V, D] = eig(C);
[~, idx] = sort(diag(D), 'descend');
V = V(:, idx);
% Project data onto first k principal components
Y = X_centered * V(:, 1:k);
This code centers the data, computes the covariance matrix, finds eigenvectors and eigenvalues, sorts them, and projects data onto the top components.
Look at the parts that repeat work based on input size.
- Primary operation: Multiplying matrices to get covariance (X_centered' * X_centered) and eigen decomposition.
- How many times: Matrix multiplication does about d * d * n steps; eigen decomposition works on d x d matrix.
As we add more samples (n) or features (d), the work changes differently.
| Input Size (n, d) | Approx. Operations |
|---|---|
| n=10, d=5 | Small matrix multiply and eigen on 5x5 matrix |
| n=100, d=50 | Matrix multiply ~50*50*100 = 250,000 steps; eigen decomposition on 50x50 matrix |
| n=1000, d=200 | Matrix multiply ~200*200*1000 = 40,000,000 steps; eigen decomposition on 200x200 matrix |
Pattern observation: Work grows linearly with number of samples n but grows faster with number of features d, especially for eigen decomposition.
Time Complexity: O(n d^2 + d^3)
This means the time grows mostly by multiplying the number of samples by the square of features, plus the cube of features for eigen calculations.
[X] Wrong: "The time depends only on the number of samples n, not on features d."
[OK] Correct: The number of features affects matrix sizes and eigen decomposition, which can be much more costly than just handling samples.
Understanding how PCA scales helps you explain performance in data analysis tasks and shows you can think about algorithm costs clearly.
"What if we used Singular Value Decomposition (SVD) directly on X instead of covariance matrix? How would the time complexity change?"
Practice
What is the main purpose of Principal Component Analysis (PCA) in MATLAB?
Solution
Step 1: Understand PCA goal
PCA finds new axes (principal components) that capture most data variation.Step 2: Identify main purpose
It reduces data dimensions by focusing on important directions, simplifying analysis.Final Answer:
To reduce the number of variables by finding main directions of data -> Option AQuick Check:
PCA = Dimensionality reduction [OK]
- Thinking PCA sorts data
- Confusing PCA with summing data
- Assuming PCA generates random data
Which MATLAB command correctly performs PCA on a data matrix X?
Solution
Step 1: Recall MATLAB PCA syntax
The functionpcareturns coefficients, scores, and variances as outputs.Step 2: Match correct syntax
Only[coeff, score, latent] = pca(X);correctly calls PCA and stores outputs.Final Answer:
[coeff, score, latent] = pca(X); -> Option CQuick Check:
Correct PCA syntax =[coeff, score, latent] = pca(X);[OK]
- Using dot notation on matrix
- Passing output names as strings
- Assigning only one output without brackets
Given the MATLAB code below, what is the size of score if X is a 100x5 matrix?
[coeff, score, latent] = pca(X);
Solution
Step 1: Understand PCA output sizes
scorecontains transformed data points in principal component space, same rows asX.Step 2: Match dimensions
SinceXis 100x5,scoreis 100x5 (100 samples, 5 components).Final Answer:
100x5 -> Option BQuick Check:
score size = samples x components = 100x5 [OK]
- Confusing score size with coeff size
- Assuming score is square matrix
- Swapping rows and columns
Identify the error in this MATLAB PCA code snippet:
X = rand(50,3);
[coeff, score, latent] = pca(X);
disp(score(1,4));
Solution
Step 1: Check size of PCA outputs
InputXhas 3 columns, soscorehas 3 columns (components).Step 2: Identify indexing error
Accessingscore(1,4)tries to get 4th column which does not exist, causing an error.Final Answer:
Indexing score at column 4 causes an error -> Option AQuick Check:
score columns = 3, index 4 invalid [OK]
- Assuming more components than input columns
- Ignoring MATLAB indexing errors
- Thinking semicolon omission causes error here
You want to reduce a dataset X (200x10) to 2 principal components using MATLAB PCA. Which code correctly achieves this?
% Options:
A) [coeff, score] = pca(X, 'NumComponents', 2);
B) [coeff, score] = pca(X, 'NumComponents', 2); score = score(:,3:4);
C) [coeff, score] = pca(X); score = score(:,11:12);
D) [coeff, score] = pca(X, 'Components', 2);
Solution
Step 1: Understand PCA dimension reduction parameter
MATLAB'spcaaccepts 'NumComponents' to limit output components.Step 2: Identify correct usage
[coeff, score] = pca(X, 'NumComponents', 2); uses correct parameter'NumComponents', 2to get 2 components directly.Step 3: Check other options
B: [coeff, score] = pca(X, 'NumComponents', 2); score = score(:,3:4); tries to slice non-existent columns 3-4; C: [coeff, score] = pca(X); score = score(:,11:12); tries to slice non-existent columns 11-12; D: [coeff, score] = pca(X, 'Components', 2); uses invalid parameter.Final Answer:
[coeff, score] = pca(X, 'NumComponents', 2); -> Option DQuick Check:
Use 'NumComponents' to limit PCA output [OK]
- Using wrong parameter name 'Components'
- Using invalid slice indices on PCA score
- Assuming PCA auto-limits components without parameter
Ready to prove it?
Pass the test and this pattern moves unknown
