Pairwise Distance Matrix

Version (499 Bytes) by Mo Chen
Compute pairwise square Euclidean or Mahalanobis distances between points sets (fully optimized!).


Updated Sun, 13 Mar 2016 12:09:20 +0000

View License

This function computes pairwise distance between two sample sets and produce a matrix of square of Euclidean or Mahalanobis distances. The code is fully optimized by vectorization. Therefore it is much faster than the built-in function pdist.
When two matrices A and B are provided as input, this function computes the square Euclidean distances between them. If an extra positive definite matrix M is provided, it computes Mahalanobis distances.

If only one matrix A is provided, the function computes pairwise square Euclidean distances between vectors in A. In this case, it is equivalent to the square of pdist function in matlab statistics toolbox but much faster.

Sample code:

Detail explanation can be found in following blog post:

This function is now a part of the PRML toolbox (

Cite As

Mo Chen (2023). Pairwise Distance Matrix (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by: Pattern Recognition and Machine Learning Toolbox

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!


Version Published Release Notes

Cleaning up
minor tweak
update description

update description

update title and description

remove any redundant error check

update to support Mahalanobis distance. fix a bug for one dimensional case.

Add a centerization step for robustness purpose. Split the code for different number of input for efficiency purpose. Update comments.

update the description