Adding nodes and edges to graph data structure dynamically in Matlab
<p>I usually create graphs in matlab as follows:</p>

<pre><code>g=sparse(5,5);
g(2,3)=1;
</code></pre>

<p>and so on.</p>

<p>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.</p>

<p>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. </p>

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

<pre><code>Add vertex v0 to graph G.
</code></pre>

<p>How can i implement this?</p>

<p>And then later a pseudo-code tells </p>

<pre><code>Add edge (v0,v1) to graph G.
</code></pre>

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

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

<p>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. </p>

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

<p><a href="http://www.mathworks.com/help/matlab/graph-and-network-algorithms.html" rel="nofollow">http://www.mathworks.com/help/matlab/graph-and-network-algorithms.html</a></p>

python algorithm matlab graph