bundles / scipy 1.18.0 / scipy / spatial / _kdtree / KDTree / sparse_distance_matrix
function
scipy.spatial._kdtree:KDTree.sparse_distance_matrix
source: /scipy/spatial/_kdtree.py:886
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. , 0.27296, 0.2546 , 0. ],
[0.06422, 0. , 0. , 0. , 0. ],
[0.19659, 0. , 0. , 0. , 0. ],
[0.13361, 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ]])
You can check distances above the `max_distance` are zeros:
from scipy.spatial.distance import cdist
✓cdist(points1, points2)
✗array([[0.92051, 0.34091, 0.27296, 0.2546 , 0.38924],
[0.06422, 0.59761, 0.93863, 0.7052 , 0.82604],
[0.19659, 0.39908, 0.70936, 0.51702, 0.59573],
[0.13361, 0.60411, 0.96603, 0.70487, 0.86201],
[0.40768, 0.44538, 0.57588, 0.56199, 0.42595]])
Aliases
scipy.spatial.KDTree.sparse_distance_matrix