squareform
Conversion between a distance vector and a symmetric distance matrix
Syntax
y = squareform(x) y = squareform(x, "tomatrix") y = squareform(x, "tovector")
Arguments
- x
a vector of length n * (n - 1) /2 or
a n x n symmetric matrix with zeros on the diagonal.
- mode
"tomatrix: forces conversion from a vector to a square matrix"tovector": forces conversion from a square matrix to a vector
- y
a n x n symmetric distance matrix (matrix mode), or
a column vector containing the upper triangular elements of the distance matrix (vector mode).
Description
squareform converts between two equivalent representations of pairwise distances.
"default mode"(squareform(x)): the conversion direction is inferred from the shape ofx."tomatrix mode"(squareform(x, "tomatrix")):xmust be a vector of lengthn*(n-1)/2.ndenotes the number of elements; the input vector therefore containsn*(n-1)/2distances, corresponding to all possible pairs among thesenelements. The function returns a n x n symmetric matrix with zeros on the diagonal."tovector mode"(squareform(x, "tovector")):xmust be a n x n square matrix. The function returns a column vector containing the upper triangular elements of x (excluding the diagonal).
This function is useful in clustering, distance-based algorithms, and statistics analysis.
Examples
Default mode
X = [0 0; 1 0; 0 2; 1 2]; d = pdist(X) // 1.000000 2.000000 2.236068 2.236068 2.000000 1.000000 D = squareform(d) // 0. 1. 2. 2.236068 // 1. 0. 2.236068 2. // 2. 2.236068 0. 1. // 2.236068 2. 1. 0. d2 = squareform(D) // 1.000000 2.000000 2.236068 2.236068 2.000000 1.000000
Forced matrix conversion ("tomatrix")
X = [0 0; 1 0; 0 1]; d = pdist(X) // 1. 1. 1.4142136 D = squareform(d, "tomatrix") // 0. 1. 1. // 1. 0. 1.4142136 // 1. 1.4142136 0.
Forced vector conversion ("tovector")
X = [0 0; 1 0; 0 1]; d = pdist(X) // 1. 1. 1.4142136 D = squareform(d) // 0. 1. 1. // 1. 0. 1.4142136 // 1. 1.4142136 0. v = squareform(D, "tovector") // 1. 1. 1.4142136
See also
- pdist — Pairwise distances between observations
History
| Версия | Описание |
| 2026.1.0 | Function added. |
| Report an issue | ||
| << polyval | Statistics | Sparse Matrix >> |