Note: This page has been translated by MathWorks. Click here to see

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Shortest path distances of all node pairs

`d = distances(G)`

`d = distances(G,s)`

`d = distances(G,s,t)`

`d = distances(___,'Method',algorithm)`

returns a matrix, `d`

= distances(`G`

)`d`

, where `d(i,j)`

is the
length of the shortest path between node `i`

and node
`j`

. If the graph is weighted (that is,
`G.Edges`

contains a variable `Weight`

), then
those weights are used as the distances along the edges in the graph. Otherwise, all
edge distances are taken to be `1`

.

optionally specifies the algorithm to use in computing the shortest path using any
of the input arguments in previous syntaxes. For example, if `d`

= distances(___,'`Method`

',algorithm)`G`

is
a weighted graph, then `distances(G,'Method','unweighted')`

ignores
the edge weights in `G`

and instead treats all edge weights as
`1`

.

The

`shortestpath`

,`shortestpathtree`

, and`distances`

functions do not support undirected graphs with negative edge weights, or more generally any graph containing a negative cycle, for these reasons:A

*negative cycle*is a path that leads from a node back to itself, with the sum of the edge weights on the path being negative. If a negative cycle is on a path between two nodes, then no shortest path exists between the nodes, since a shorter path can always be found by traversing the negative cycle.A single negative edge weight in an undirected graph creates a negative cycle.

`digraph`

| `graph`

| `nearest`

| `shortestpath`

| `shortestpathtree`

Was this topic helpful?