Skip to main content
v2026.11,986 entries · CC-BY 4.0

Pearson Correlation in MATLAB: corrcoef and corr

Compute Pearson r and p-values in MATLAB with corrcoef or corr, handle NaN rows, read R, P, RL and RU, and report results.

Written and maintained by CASRAI Editorial Board

Published

On this page

To compute a Pearson correlation in MATLAB, pass your data to corrcoef (base MATLAB) or corr (documented in Statistics and Machine Learning Toolbox): [R,P] = corrcoef(A) returns the matrix of Pearson coefficients and the matching p-values, with each column of A treated as a variable and each row as an observation. corr uses the Pearson type by default, but its two-input form behaves differently from corrcoef, which is the most common source of wrong answers.

What Pearson correlation in MATLAB is used for in research

The Pearson correlation coefficient measures the strength and direction of the linear association between two numeric variables, on a scale from -1 to 1. Researchers use it to screen a set of measured variables for related pairs, to check that two instruments or two scoring methods agree in rank-free linear terms, and to report effect sizes alongside a regression. It is a measure of linear association only: a curved relationship can give a coefficient near zero, so inspect a scatter plot first (see how to interpret a scatterplot) and compare it with other coefficients in types of correlation. For the definition, assumptions and interpretation of the coefficient itself, see the correlation coefficient guide.

MATLAB documents the quantity in corrcoef as the covariance of the two variables divided by the product of their standard deviations, written as ρ(A,B) = 1/(N-1) × Σ[(Ai − μA)/σA] × [(Bi − μB)/σB] = cov(A,B)/(σAσB), where μ and σ are the mean and standard deviation of each variable and N is the number of observations.

Assumptions to check before you report r

The coefficient describes a linear relationship, and it is sensitive to extreme values, so check for outliers and curvature in a plot. The Pearson p-value in SciPy’s documentation assumes the two variables are drawn from normal distributions, and that page also notes that a zero correlation implies independence only when the variables are jointly normal. Treat the same caution as applying to any Pearson p-value, including MATLAB’s. If the data are ordinal, heavily skewed or contain influential outliers, the Spearman and Kendall options of corr (below) answer a different, rank-based question.

How to install or access MATLAB

MATLAB is a MathWorks product, and access is arranged through MathWorks: start from the MATLAB product page on mathworks.com, or through your institution’s site licence if it has one. The function corrcoef is documented in the base MATLAB reference. The function corr is documented in the Statistics and Machine Learning Toolbox section of the MathWorks help, so confirm it is available in your installation before relying on it in a script. If it is not, corrcoef gives the same Pearson matrix for a single input matrix.

How to compute Pearson correlation in MATLAB step by step

  1. Arrange the data. Put one variable per column and one observation per row in a numeric matrix A. For two separate variables, use two column vectors of the same length.
  2. Compute the matrix. Run R = corrcoef(A). For a single input, R is size(A,2)-by-size(A,2), symmetric, with ones on the diagonal.
  3. Ask for p-values. Run [R,P] = corrcoef(A). P tests the null hypothesis of no relationship and is the same size as R; off-diagonal values below Alpha (default 0.05) indicate a significant correlation.
  4. Ask for confidence bounds. Run [R,P,RL,RU] = corrcoef(A). RL and RU are the lower and upper bounds of the confidence interval for each coefficient, 95% by default. Set a different level with corrcoef(A,'Alpha',0.01), which widens the bounds relative to the default 0.05 setting.
  5. Choose how missing values are handled. Add the Rows option, for example corrcoef(A,'Rows','complete'). The three settings are described in the troubleshooting section.
  6. Use corr when you need the Pearson, Spearman or Kendall type. rho = corr(X) correlates the columns of X; [rho,pval] = corr(X,Y,'Type','Pearson') correlates each column of X with each column of Y and returns p-values. The documented types are 'Pearson' (the default), 'Kendall' (tau-b) and 'Spearman'.

corr versus corrcoef with two inputs

With two matrices, the two functions do not return the same thing. corr(X,Y) returns a column-by-column matrix, one coefficient for each pairing of a column of X with a column of Y. corrcoef(X,Y) flattens both inputs to X(:) and Y(:) and returns a single 2-by-2 matrix, so with matrix inputs the results can differ substantially. If you want per-variable coefficients between two sets of columns, use corr, or pass [X Y] to corrcoef and read the off-diagonal block.

Worked example: five observations by hand

Take x = [1 2 3 4 5] and y = [2 4 5 4 5]. The means are 3 and 4, so the deviations are x: −2, −1, 0, 1, 2 and y: −2, 0, 1, 0, 1. The sum of products of deviations is 4 + 0 + 0 + 0 + 2 = 6, the sum of squared x deviations is 10 and the sum of squared y deviations is 6. The coefficient is 6 / √(10 × 6) = 6 / √60 ≈ 0.7746. In MATLAB, corrcoef([1 2 3 4 5],[2 4 5 4 5]) returns a 2-by-2 matrix with ones on the diagonal and this value, about 0.7746, off the diagonal.

Worked example: the MathWorks simulated data set

The MathWorks documentation builds a 50-by-6 matrix of random normal numbers (see randn in MATLAB) and makes some columns depend on others, then extracts the significant pairs:

rng(16)
A = randn(50,6);
A(:,3) = A(:,3) + 2*A(:,1);
A(:,4) = A(:,4) - 3*A(:,2);
A(:,5) = A(:,6) + 0.1*A(:,4) - 0.1*A(:,3);
[R,P] = corrcoef(A);
R = tril(R,-1);
threshold = 0.05;
R(abs(P) > threshold) = 0;
[firstVar,secondVar,corrCoef] = find(R);
ind2 = sub2ind(size(P),firstVar,secondVar);
sigP = P(ind2);
TSig = table(firstVar,secondVar,corrCoef,sigP)

The page prints four significant pairs: variables 3 and 1 (r = 0.80471, p = 1.8997e-12), 4 and 2 (r = −0.96118, p = 1.7065e-28), 5 and 3 (r = −0.35949, p = 0.010346) and 6 and 5 (r = 0.9384, p = 8.5819e-24). The first two follow directly from how the columns were built. This is MathWorks’ own illustrative simulation, so the values are a check that your installation reproduces the documented output, not a research result.

How to read the output

Read R first. Each entry is the coefficient between the variable in that row and the variable in that column; the diagonal is always 1 and the matrix is symmetric, so only the lower or upper triangle carries information (the example above uses tril(R,-1) to keep the lower triangle without the diagonal). Values near 1 or −1 indicate a strong linear association, with the sign giving the direction, and values near 0 indicate little linear association.

Read P next. A value below Alpha indicates a correlation that is significant at that level, and very small values such as 1.7065e-28 are printed in scientific notation. Then read RL and RU: the interval from RL to RU shows how precisely each coefficient is estimated, and a smaller Alpha gives wider bounds.

Reporting the result

A common reporting pattern gives the coefficient with its degrees of freedom (N − 2 for a Pearson correlation of two variables), the p-value and, where available, the interval. For the first significant pair above, with N = 50 observations, that reads r(48) = .80, p below .001, 95% CI from RL to RU. Report the sample size, the missing-data setting you used and whether you ran many pairwise tests, because a matrix of many p-values contains false positives by chance. Plot the pair before you report it, and name the function and options in your methods text.

Troubleshooting MATLAB correlation

Every off-diagonal value is NaN

The default Rows setting is 'all', which includes NaN values in the computation. A NaN in a column therefore spreads through that column’s coefficients; in the MathWorks NaN example every off-diagonal entry is NaN with this setting. Use 'complete' to omit every row that contains a NaN, or 'pairwise' to omit rows only for each pair of columns.

Complete or pairwise deletion

The documentation states that 'complete' always returns a positive semi-definite matrix, while 'pairwise' may not. In the MathWorks example the two settings give noticeably different coefficients for the same data (for instance about −0.85, 0.82 and −0.9987 under 'complete' against about −0.34, 0.46 and −0.9987 under 'pairwise'), so state which one you used. corr accepts the same three Rows settings, with 'all' as the default.

A row and column of NaN with no missing data

If one variable is constant, its correlations are undefined and its row and column in R are NaN. Check std(A) for a column of zeros. Similarly, a scalar input returns NaN and a vector input returns 1.

Errors when requesting P, RL or RU

The P, RL and RU syntaxes are invalid when R contains complex values. With corrcoef(A,B), A and B must be the same size.

One-sided p-values

corr has a Tail option: 'both' (default), 'right' or 'left'. State the tail you used when you report a one-sided test.

Free alternatives to MATLAB

Two free alternatives expose the same calculation with documented behaviour; the table compares them with the MATLAB functions. For the R route see how to build a correlation matrix in R, and for the Python array route see NumPy corr. The data table below compares the functions documented by MathWorks, GNU Octave and SciPy.

Tool and function What it returns How it handles missing values or constant input
GNU Octave corr(x,y) Correlation between the columns of x and y, computed as cov(A,B) / (std(A) * std(B)); each row is an observation and each column a variable A scalar or single-row input returns NaN, because the standard deviation is zero
GNU Octave corrcoef(x,y) Pearson coefficients, with optional p-values and lower and upper confidence bounds; alpha default 0.05 rows option: "all" (default), "complete" or "pairwise"
SciPy scipy.stats.pearsonr(x, y) A statistic and a p-value; a confidence_interval() method on the result gives the interval Constant input gives a ConstantInputWarning and a NaN result

The Octave manual lists these functions in its Statistics chapter without stating which package provides each, so check your Octave installation. For SciPy, the documented p-value assumes normally distributed data, as noted earlier.

Sources

Data: Pearson correlation functions in MATLAB, GNU Octave and SciPy

Compares the documented behaviour of MATLAB corrcoef and corr, GNU Octave corr and corrcoef, and SciPy pearsonr: default correlation type, p-value output, confidence bounds, missing-value handling and two-input behaviour. Compiled from each project's own reference documentation.

Pearson correlation functions in MATLAB, GNU Octave and SciPy
FunctionDefault correlation typeP-value outputConfidence boundsMissing-value handlingTwo-input behaviour
MATLAB corrcoefPearsonSecond output PThird and fourth outputs RL, RU (Alpha default 0.05)Rows: all (default), complete, pairwiseFlattens inputs to X(:), Y(:) and returns one 2-by-2 matrix
MATLAB corr (Statistics and Machine Learning Toolbox)Pearson (also Kendall, Spearman)Second output pval; Tail both (default), right, leftNot listed in the syntax readRows: all (default), complete, pairwiseColumn-by-column matrix between columns of X and columns of Y
GNU Octave corrcoefPearsonSecond output pThird and fourth outputs lci, hci (alpha default 0.05)rows: all (default), complete, pairwiseCoefficients for x and y as variables
GNU Octave corrCorrelation as cov(A,B) / (std(A) * std(B))Not in the documented syntaxNot in the documented syntaxScalar or single-row input returns NaNCorrelation between each column of x and each column of y
SciPy stats.pearsonrPearsonpvalue attribute (assumes normal distributions)confidence_interval() methodConstant input gives ConstantInputWarning and NaNTwo arrays x and y of length 2 or more

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Pearson Correlation in MATLAB: corrcoef and corr

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →