简体   繁体   中英

Adding nodes and edges to graph data structure dynamically in Matlab

I usually create graphs in matlab as follows:

g=sparse(5,5);
g(2,3)=1;

and so on.

This works very well if i have the graph created in advance and given to me figuratively so that i have to make a adjacency matrix representing that graph. But now i have a different kind of problem. I have to create the graph from scratch dynamically. I have a bunch of nodes, say 500 nodes. Now i have to loop over these 500 nodes and if certain conditions are satisfied i will put some of the nodes, say 200 in my graph structure. Then i will run a loop over different pairs of nodes in this pool of 200 nodes and if certain conditions are satisfied, then i will add an edge.

I am working in Matlab and one method i could figure was that i will just intialise an adjacency matrix of size 500x500. And just add edges for the ones that pass the criterion. This is undesirable. I don't want to include the 500 points in my graph structure at all.

Basically, I want to do this in Matlab. In pseudo-codes in research papers, it is told:

Add vertex v0 to graph G.

How can i implement this?

And then later a pseudo-code tells

Add edge (v0,v1) to graph G.

And lastly if there is already an edge in the graph (v0,v1) and you are told:

Delete edge (v0,v1)  % Not asking you to delete the nodes.
Add node v.
Add edges (v0,v) and (v,v1)

I want to do these steps efficiently. I want to be able to create my graph dynamically. I don't want to create a huge adjacency matrix and then designate edges in it. I want to build my graph step-by-step if needed. If this can be done in Matlab please let me know. Otherwise i am open to python also.

Have you tried looking into MATLAB's new-ish graph class? It was introduced in R2015b and has methods you can use to do these steps efficiently. Specifically, it has addnode , addedge , rmedge , etc. You can also extract the adjacency matrix from the graph object with adjacency .

http://www.mathworks.com/help/matlab/graph-and-network-algorithms.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM