pca — Principal components of real observation matrices.
Compute principal directions, scores, component variances and Hotelling statistics through singular value decomposition.
Syntax
[coeff,score,latent,tsquared,explained,mu] = pca(X,Name,Value,...)Inputs
X- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Real single/double matrix, observations by variables.
name_value_pairs- Type
Any- Required
- Variadic
- Default
- —
- Description
- Algorithm, Centered, Economy, NumComponents and Rows options.
Returns
coeff- Type
NumericArray- Description
- Principal directions, variables by returned score components.
score- Type
NumericArray- Description
- Observation scores with excluded rows reinserted as NaN.
latent- Type
NumericArray- Description
- Component variances, column vector, independent of score truncation.
tsquared- Type
NumericArray- Description
- Hotelling T-squared over all degrees-of-freedom-admissible PCs, before NumComponents truncation.
explained- Type
NumericArray- Description
- Percentage variance explained, with the same extent as latent.
mu- Type
NumericArray- Description
- Variable means, or zeros when Centered is off.
Errors
RunMat:pca:InvalidArgument- When
- Class, matrix geometry, retained finite observations/degrees of freedom, supported options, device intent or output count is invalid.
- Message
pca: invalid argument
Data and computation
Rows of X are observations and columns are variables. Real single and double matrices are supported. The default centers each variable, removes incomplete rows, and uses the existing SVD factorization, not an independently approximated covariance matrix. Loadings are ordered by descending singular values; the largest-magnitude loading in each returned component has positive sign.
All six output arrays retain X's floating class. The host factorization and statistical workspaces use binary64, with one final conversion for single outputs. Integer, logical, complex, sparse, distributed, and explicit gpuArray observation arrays are unsupported; these are not silently converted or advertised as additional overloads.
Rows='complete' omits rows containing NaN, then reinserts NaNs at those observation positions in score and tsquared. Centering means use all available non-NaN observations in each original column, even in rows excluded because another column is missing. Rows='all' rejects NaN observations. Retained infinities, or infinities contributing to centering means, are invalid. Positive degrees of freedom are required after omission: at least two retained rows when centered, or one when uncentered.
Options and six outputs
Supported case-insensitive name/value options are Algorithm='svd', Centered, Economy, NumComponents, and Rows='complete' or 'all'. Centered and Economy accept logical scalars or on/off text. NumComponents is a positive single/double scalar integer no greater than the number of variables. Later repeated options replace earlier values. Unsupported options and values raise errors; weights, VariableWeights, eig/als algorithms, pairwise covariance and iterative missing-data estimation are not accepted and ignored.
[coeff,score,latent,tsquared,explained,mu] returns principal directions, observation scores, component variances, full-space Hotelling T-squared, percentage variance explained, and variable means. Centered='off' returns a zero mean row and uses the retained row count as degrees of freedom; centered analysis uses one fewer.
Economy defaults to true and limits variances and components to min(degrees of freedom,variables). Economy=false retains all variance entries and orthonormal loading directions, with zero variance/score padding beyond the degrees-of-freedom bound. NumComponents limits coeff/score, but does not truncate latent, explained, or T-squared over all degrees-of-freedom-admissible PCs. With Economy=false, a requested component count at least as large as the degrees of freedom returns the full variable-space basis. With incomplete rows, all-available column means can make the retained matrix's raw rank exceed that degrees-of-freedom bound; the bound is still applied and padded directions are not claimed to be its covariance nullspace.
T-squared excludes numerical null directions using the shared rank/pinv SVD tolerance; no covariance eigenvalues are clamped to positive values. Explained percentages use normalized singular values, independent of overflow/underflow in displayed variances. An all-zero variance spectrum has NaN explained percentages and zero full-space T-squared; degenerate eigenspaces may have different, equally valid orthonormal bases.
Residency, cancellation and resources
Only authenticated automatic residency can use the context-owned host gather fallback, including numeric controls. Explicit or unproven device intent is rejected before any argument transfer; use gather explicitly for host analysis. There is no provider-native PCA kernel or fusion producer.
Finite host-memory requests are rejected before gather or SVD workspace allocation because the factorization and output workspaces have no complete allocation certificate. Input/output scans cooperate with the original execution context. The existing dense SVD kernel is synchronous between cancellation checkpoints and is not claimed to be hard-preemptible. Original gather, factorization and typed cancellation errors are not replayed or relabeled. Unrequested public output arrays are not constructed.
Examples
Analyze two orthogonal variables
X = [-1 -1;-1 1;1 -1;1 1]; [C,S,L,T,E,M] = pca(X);Retain one score direction
X = [-2 -1;0 2;2 -1]; [C,S,L,T,E,M] = pca(X,'NumComponents',1);Using pca with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how pca changes the result.
Run a small pca example, explain the result, then change one input and compare the output.
Related Stats functions
Summary
anova1 · binocdf · binscatter · boxplot · cdf · cdfplot · chi2cdf · corr · corrcoef · corrcov · cov · cov2corr · dummyvar · ecdf · filloutliers · fitdist · geomean · grpstats · harmmean · icdf · isoutlier · ksdensity · kstest · kurtosis · lsline · mad · mode · nanmax · normalize · normcdf · norminv · normpdf · onehotdecode · onehotencode · pdf · prctile · qqplot · quantile · refline · rmse · scatterhist · skewness · tabulate · tcdf · tiedrank · tinv · tpdf · ttest · ttest2 · wblinv
Ml
bayesopt · classify · confusionmat · crossvalind · cvpartition · fitclinear · fitctree · fitlm · kmeans · knnsearch · lasso · lassoglm · linkage · lscov · mnrfit · nlparci · optimizableVariable · pdist · pdist2 · perfcurve · predict · regress · ridge · squareform · test · training · tsne
Random
binornd · bootstrp · datasample · dividerand · exprnd · gamrnd · gpurng · lhsdesign · mvnrnd · normrnd · random · randsample · rng · trnd · unidrnd · unifrnd · wblrnd
Hist
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.