Scilab Website | Contribute with GitLab | Scilab Community | ATOMS toolboxes
Scilab Online Help
2026.1.0 - Русский


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 of x.

  • "tomatrix mode" (squareform(x, "tomatrix")): x must be a vector of length n*(n-1)/2. n denotes the number of elements; the input vector therefore contains n*(n-1)/2 distances, corresponding to all possible pairs among these n elements. The function returns a n x n symmetric matrix with zeros on the diagonal.

  • "tovector mode" (squareform(x, "tovector")): x must 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 >>

Copyright (c) 2022-2026 (Dassault Systèmes S.E.)
Copyright (c) 2017-2022 (ESI Group)
Copyright (c) 2011-2017 (Scilab Enterprises)
Copyright (c) 1989-2012 (INRIA)
Copyright (c) 1989-2007 (ENPC)
with contributors
Last updated:
Tue May 19 14:01:45 CEST 2026