Note: This page has been translated by MathWorks. Please click here

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

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

Shortest path between two single nodes

`P = shortestpath(G,s,t)`

`P = shortestpath(G,s,t,'Method',algorithm)`

```
[P,d] =
shortestpath(___)
```

computes the shortest path starting at source node `P`

= shortestpath(`G`

,`s`

,`t`

)`s`

and ending
at target node `t`

. 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`

.

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`

| `distances`

| `graph`

| `nearest`

| `shortestpathtree`

Was this topic helpful?