Can I preserve adding order when calling graph/addedge?

Hi when calling graph/addedge. The added edge are re-ordered from the adding order. For example:
>> g = graph;
>> g = graph;
>> g = g.addedge(5, 6);
>> g = g.addedge(1, 2);
>> g.Edges
ans =
2×1 table
EndNodes
________
1 2
5 6
Is there a way to avoid this re-order?
This question comes from a requirement that I would like to remember indices of some edges for quick access. However, if calling addedge the indices will be then dis-ordered. It is not suitable to look up edge by EndNodes in my case because the graph can contain multi-edges.

 採用された回答

Christine Tobler
Christine Tobler 2020 年 2 月 24 日

1 投票

The edges in a graph are always presented in the same order (sort first by source node, secondarily be target node). You can maintain an index into the previous numbering of the edges by adding a new property that tracks this:
>> g = graph;
>> g = addedge(g, 5, 6, 1);
>> g = addedge(g, 1, 2, 2);
>> g.Edges
ans =
2×2 table
EndNodes Weight
________ ______
1 2 2
5 6 1

3 件のコメント

Bo
Bo 2020 年 2 月 24 日
Thanks Christine. Yes this is a workaround. The problem is that retrieving an edge by this property would be a O(n) operation. Would there be anything faster?
Christine Tobler
Christine Tobler 2020 年 2 月 25 日
Hi Bo,
If you keep the graph around without modifying, you could do
edgeOrder(g.Edges.Weight) = 1:numedges(g)
This will give you a direct mapping from the order in which you entered the edges into g, to the index that they have been assigned.
That's O(n) in constructing edgeOrder, and then O(1) in accessing an individual edge.
Bo
Bo 2020 年 2 月 25 日
Thanks. This is handy. Yes though I guess retrieving edges is not easy to handle when the graph is growing.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeGraph and Network Algorithms についてさらに検索

質問済み:

Bo
2020 年 2 月 24 日

コメント済み:

Bo
2020 年 2 月 25 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by