bundles / scipy 2.0.0.dev0+git20260907.41eeb59 / scipy / spatial / _kdtree / KDTree / sparse_distance_matrix
function
scipy.spatial._kdtree:KDTree.sparse_distance_matrix
source: build-install/usr/lib/python3.14/site-packages/scipy/spatial/_kdtree.py:888
Signature
def sparse_distance_matrix(self, other, max_distance, p = 2.0, output_type = dok_matrix)Summary
Compute a sparse distance matrix.
Extended Summary
Computes a distance matrix between two KDTrees, leaving as zero any distance greater than max_distance.
Parameters
other: KDTreeThe other KDTree to compute distances against.
max_distance: positive floatMaximum distance within which neighbors are returned. Distances above this value are returned as zero.
p: float, 1<=p<=infinityWhich Minkowski p-norm to use. A finite large p may cause a ValueError if overflow can occur.
output_type: str, optionalWhich container to use for output data. Options:
'dok_array','coo_array','dict', or'ndarray'. Legacy options'dok_matrix'and'coo_matrix'are still available. Default:'dok_matrix'.
Returns
result: dok_array, coo_array, dict or ndarraySparse matrix representing the results in "dictionary of keys" format. If a dict is returned the keys are
(i,j)tuples of indices. If output_type is'ndarray'a record array with fields'i','j', and'v'is returned,
Examples
You can compute a sparse distance matrix between two kd-trees:import numpy as np from scipy.spatial import KDTree rng = np.random.default_rng() points1 = rng.random((5, 2)) points2 = rng.random((5, 2)) kdtree1 = KDTree(points1) kdtree2 = KDTree(points2) sdm = kdtree1.sparse_distance_matrix(kdtree2, 0.3, output_type="dok_array")✓
sdm.toarray()
✗array([[0. , 0.2656 , 0.09461, 0. , 0. ],
[0.28102, 0. , 0. , 0. , 0.22114],
[0. , 0.13343, 0. , 0. , 0. ],
[0.06543, 0. , 0. , 0. , 0.1466 ],
[0. , 0. , 0. , 0.21614, 0. ]])
You can check distances above the `max_distance` are zeros:
from scipy.spatial.distance import cdist
✓cdist(points1, points2)
✗array([[0.32609, 0.2656 , 0.09461, 0.53946, 0.50757],
[0.28102, 0.69213, 0.42826, 0.96537, 0.22114],
[0.51319, 0.13343, 0.35299, 0.3065 , 0.69554],
[0.06543, 0.49247, 0.30883, 0.75715, 0.1466 ],
[0.80035, 0.45235, 0.80075, 0.21614, 0.93065]])
Aliases
scipy.spatial.KDTree.sparse_distance_matrix